Quote:
Originally Posted by subham
When I set the stack base address of the child thread using the POSIX library function "pthread_attr_setstackaddr()", I am unable to access the memory contents of its parent. The data-structures that are created on the HEAP of its parent using malloc() are either getting destroyed or unaccessible when moving to the context of the child thread.
|
You should be using
pthread_attr_setstack, since
pthread_attr_setstacksize and
pthread_attr_setstackaddr are now deprecated.
The most likely reason for your error is because the
pthread_attr_setstackaddr does not set the base of the stack, but the initial stack pointer. On an x86 architecture and many others, this is the
end of the allocated stack space (which is why it is non-portable and is now deprecated).
If you set it to the start of the allocated space, the stack will grow down into other memory and cause heap corruptions. Depending on your architecture, you could have used
pthread_attr_setstackaddr(tattr, stackbase+stacksize) to fix your memory corruption.
The example below illustrates a child accessing the heap of the parent, with no issues.
Code:
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
void *threadFn(void *arg)
{
// print string
puts((char *) arg);
}
int main()
{
// create a string on the heap
char *arg = malloc(3);
arg[0] = '4'; arg[1] = '2'; arg[2] = 0;
// create a stack
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setstack(&attr, malloc(4096), 4096);
// start child thread
pthread_t thread;
pthread_create(&thread, &attr, threadFn, arg);
pthread_attr_destroy(&attr);
pthread_join(thread, 0);
}