Saturday, September 22, 2018
c - How does free() know how much memory to deallocate?
Answer
Answer
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?
Answer
The most common way is that it stores some information immediately before the address it returns to you. So if malloc returns the address 0x1004, internally, malloc will have put aside the memory started at 0x0FFC and will store various information such as the size somewhere in the memory between 0xFFC - 0x1003 but the application will be told the allocation starts at 0x1004.
The only thing that matters to free is getting the exact same address as what malloc returned.
plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV
In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...
-
This question attempts to collect the few pearls among the dozens of bad C++ books that are published every year. Unlike many other programm...
-
I need to do the following: My current address looks like: https://www.domain.com I want to redirect with htaccess: www.domain.com TO https:...
-
String response = getResultForRequest(url); Where 'url' is JSON formatted which return bunch of data using http GET method. public s...
No comments:
Post a Comment