When creating a new pthread and passing it an argument modified with pthread_attr_getstack it seems to not using the defined stack space.
void* thread_function(void * ptr)
{
int a;
printf("stack var in thread %p\n",&a);
}
int main( int argc , char **argv )
{
pthread_t thread;
void * ptr = NULL;
const int stack_size = 10*1024;
void * stack = malloc(stack_size);
printf("alloc=%p\n",&stack);
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setstack( &attr , stack , stack_size );
if (pthread_create(&thread, &attr, &thread_function , ptr ) ) {
printf("failed to create thread\n");
return 1;
}
pthread_attr_destroy(&attr);
pthread_exit( 0 );
return 0;
}
Unfortunately the output is:
alloc=0x7fff48989bc8
stack var in thread 0x7f6e6f0d2ebc
Even if stack grows backward (which i am not sure) the pointer values differ so much, that only hope that the created thread uses a different virtual memory address space. But i think this is not the case.
You’re printing the wrong thing,
Prints the address of a local stack variable, not the allocated memory. You have to do
Also, you need to check for errors:
You’ve only set a stack of 10kB, so try again with a bigger stack, and check the return value of pthread_attr_setstack.
I’d probably try to make the stack page aligned as well.