1

I have a program that takes input n from the command line, and, as part of its operation, tries to call the following code:

pthread_t threads[n*n];

Now, for any n <= 1023, this works fine, but the moment I try to use n > 1023, I get a segfault. It is this particular line that causes it - my code does not advance beyond it. I'm a little confused as to why this is happening, and would appreciate all possible help.

4

1 回答 1

2

这是因为数组的大小(即指针大小乘以 2^20)太大而无法保存在自动内存中(即堆栈上)。您可以通过使用动态分配来解决此问题:

pthread_t *threads = malloc(sizeof(pthread_t) * n * n);

当然,一旦你完成了数组,你需要释放这个内存:

free(threads);
于 2014-10-25T03:27:10.750 回答