Search code examples
csegmentation-faultpthreadsvariable-length-array

Segfaults on initialization of array of pthread_t


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.


Solution

  • This is because the size of the array (i.e. the size of the pointer times 2^20) is too large to be held in the automatic memory (i.e. on the stack). You can fix this by using dynamic allocation:

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

    Of course you need to free this memory once you are done with the array:

    free(threads);