what happens when tried to free memory allocated by heap manager, which allocates more than asked for?

后端 未结 5 2132
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-15 10:45

This question was asked to me in an interview.

Suppose char *p=malloc(n) assigns more than n,say N bytes of memory are allocated and free(p) is used to free the memory a

5条回答
  •  死守一世寂寞
    2021-02-15 10:50

    Yes, the heap manager is allowed to return a block of more than n bytes. It is completely safe (and required!) to free the returned pointer using free, and free will deallocate all of it.

    Many heap implementations track their allocations by inserting blocks of metadata into the heap. free will look for that metadata to determine how much memory to deallocate. This is implementation-specific, though, so there's no way to know how much malloc gave you, and generally, you shouldn't care.

提交回复
热议问题