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

后端 未结 5 2140
佛祖请我去吃肉
佛祖请我去吃肉 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.

    0 讨论(0)
  • 2021-02-15 11:00

    Generally the heap manager will free whatever it allocated. It stores this info somewhere, and looks it up when free() is called.

    A heap manager is not "faulty" if it allocates more memory than was requested. Heap managers often work with fixed block sizes, and will round up to the next appropriate block size when satisfying a request. The heap manager's job is to be as efficient as possible, and often big efficiencies result from a few small inefficiencies.

    0 讨论(0)
  • 2021-02-15 11:03

    Other answers have explained well how the block size is handled. To find out how much memory is freed, the only solution I can think of is to call mallinfo() before and after the free.

    0 讨论(0)
  • 2021-02-15 11:04

    This is the default behavior of malloc. It will return NULL or a pointer to a section of memory at least as long as the one you asked for. So yes free must be able to handle getting rid of memory longer than what was asked for.

    Finding out how much memory was actually free or allocated is a platform specific question.

    0 讨论(0)
  • 2021-02-15 11:13

    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.

    0 讨论(0)
提交回复
热议问题