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

后端 未结 5 2113
忘了有多久
忘了有多久 2021-02-15 10:48

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 11:17

    Yes, that's what happens almost every time do you a malloc(). The malloc block header contains information about the the size of the block, and when free() is called, it returns that amount back to the heap. It's not faulty, it's expected operation.

    A simple implementation might, for instance, store just the size of the block in the space immediately preceding the returned pointer. Then, free() would look something like this:

    void free(void *ptr)
    {
        size_t *size = (size_t *)ptr - 1;
    
        return_to_heap(ptr, *size);
    }
    

    Where return_to_heap() is used here to mean a function that does the actual work of returning the specified block of memory to the heap for future use.

提交回复
热议问题