Possible Duplicate:
C programming : How does free know how much to free?
When programming in C, I often usemalloc()
to allocate memory and free()
to release it:
MyObject* objArr= (MyObject*) malloc(sizeof(MyObject)*numberOfObjects);
/** Do stuff **/
free(objArr);
How does free()
know how much memory to deallocate? Does malloc()
create a table somewhere to remember pointers and how much memory each pointer pointed to?
If that is the case, will free()
fail if I rename the pointer? e.g.:
MyObject* objArr= (MyObject*) malloc(sizeof(MyObject)*numberOfObjects);
MyObject* newPtr= objArr;
free(newPtr); /** Does this fail? **/
What will happen if I increment the pointer and then run free()
? e.g.:
MyObject* objArr= (MyObject*) malloc(sizeof(MyObject)*numberOfObjects);
newPtr++;
free(newPtr); /** What happens now? **/
Will it deallocate an additional chunk of memory just off the end of the original array?