A very basic conceptual doubt.
Please don’t hate me for this silly question
If we call a function like below from a thread in my main function
char * function()
{
char message[10];
.................
....do sth ......
return message;
}
In this case the internal buffer is automatic and vanishes as soon as the thread function returns.
But on doing this it works
char * function()
{
char * message = (char*)malloc(10);
.................
....do sth ......
return message;
}
I am confused with the lines below. How this solves the problem ?
Each thread will allocate a different array and store the address of that array in a stack variable. Every thread has its own stack so automatic data objects are different for each thread.
This comment does not relate to your second code snippet. what this comment means is that since each thread has it’s own stack; if multiple threads simultaneously call into the same function, they push local variables onto their own respective stacks, so no conflicts arise.
Infact your second code snippet works because each time the function is called, you are dynamically allocating new heap memory and returning a pointer to it.
NB: it’s usually nice to de-allocate the memory once you’re done with it 🙂
Also: re your first code snippet & james’ & corbin’s comments above; this function, while somewhat doubtful is not invalid ~for example, see here