Possible Duplicate:
C Array Instantiation – Stack or Heap Allocation?
When dynamically allocating a struct containing a char pointer, what happens with the actual char pointer? Where is it stored?
And once the struct is freed, is the char pointer freed along with it?
For example consider the following struct:
struct mix
{
int a;
float b;
char *s;
};
typedef struct mix mix;
And then the following code that allocates memory for it:
int main()
{
mix *ptr = (mix*)malloc(sizeof(mix));
ptr->a = 3;
ptr->b = 4.5f;
ptr->s = "Hi, there, I'm just a really long string.";
free(ptr);
return 0;
}
Is *s allocated on the stack and then freed along with *ptr? I can imagine it is indeed allocated on the stack as it’s not in any way dynamically allocated (unless malloc has some functionality I’m not aware of). And I guess ‘going out of scope’ for *s would be at the point of freeing *ptr. Or have I got it completely wrong? 🙂
Thanks very much!
The space for the
char*member namedsis allocated on the heap, along with the rest of the members ofmixafter the call tomalloc()(whose return value you do not need to cast). The string literal to whichsis assigned is not allocated on the heap or the stack, but is part of the actual binary and has static storage duration. So this:assigns the address of the string literal to
ptr->s. If you wantptr->sto point to something other than a string literal then you need tomalloc()memory for it. And for everymalloc()there must be afree()soptr->swould need to befree()d beforeptris (ifptr->sis pointing to dynamically allocate memory only).After the call to
free(), dereferencingptris undefined behaviour.