Segfault occurs on initialization in pthread only

I cannot understand why the following pseudo code is causing a segfault.

Using pthreads to run a function I run into a SEGFAULT initializing an integer to zero.

When my_threaded_function not in threaded context or if I called function from the main thread there is no issue.

The SEGFAULT doesn't occur on initializing rc=0; bu only inside the maze_init function.

I have confirmed that I am out of stack space. But I can't think of what is causing the function to behave differently inside the pthread (no shared memory involved), the address &aa cannot be accessed according to gdb.

Why would a stack variable's address not be on the stack?

int maze_init(Maze*m, char* filename)
{
   FILE *fp;
   int aa, bb, rc; 
   aa = 0;              /// SEGFAULT HERE
   ...
   return 1; 
}

void* my_threaded_function(void* arg)
{ 
   Maze maze;
   int rc;
   rc = 0;

   rc = maze_init(&maze,"test.txt");
   return rc;
   pthread_exit((void*)1);
}

int main(int argc,char** argv){
   pthread_t t;
   pthread_create(&t, NULL, my_threaded_function,(void*)0);
   sleep(10);
}
  • edit (fixed code typo to return rc )

  • I have confirmed that I am out of stack space. But I can't think of what is causing the function to behave differently inside the pthread

    Well for one by default secondary threads have smaller stacks than the "main" thread. You can set the size with pthread_attr_setstacksize .

    TLPI says:

    Each thread has its own stack whose size is fixed when the thread is created. On Linux/x86-32, for all threads other than the main thread, the default size of the per-thread stack is 2 MB. The main thread has a much larger space for stack growth

    So that is one reason why it would work when called normally and fail when called from a secondary thread.

    链接地址: http://www.djcxy.com/p/80274.html

    上一篇: 使用虚拟内存切换上下文?

    下一篇: Segfault仅在pthread初始化时发生