Sunday, April 15, 2012

Difference between mallocing and local variables

It is interesting to see what is the difference between these two types of variable declarations
char* name = malloc(256*sizeof(char));
// more code
 char name[256];
 Has been nicely explained on stackoverflow:
In the first code, the memory is dynamically allocated on the heap. That memory needs to be freed with free(). Its lifetime is arbitrary: it can cross function boundaries, etc.
In the second code, the 256 bytes are allocated on the stack, and are automatically reclaimed when the function returns (or at program termination if it is outside all functions). So you don't have to (and cannot) call free() on it. It can't leak, but it also won't live beyond the end of the function. Choose between the two based on the requirements for the memory.


Post a Comment