开发者

how does 'free/delete' work? [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicates:

How does delete work in C++?

C programming : How does free know how much to free?

For every dynamic memory allocation, using 'malloc / new', we have methods, 'free / delete' to free the allocated memory.

My question is if the memory allocation size is decieded at runtime and the memory locations not being contiguous, how does these me开发者_开发百科mory freeing methods know how much memory to free and what are the memory locations to be cleared ?

What makes these functions work if we are passing them only a pointer to single location ?


They keep track of how much memory you've allocated where internally.


When malloc/new allocates memory it also records where and how much memory it allocated for a pointer to a given memory location. free/delete looks up what memory to deallocate when you give it a pointer.

That is why you should never try to free a pointer that you moved with "+=" or something like that.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜