Why does `free` in C not take the number of bytes to be freed?

前端 未结 12 1592
情歌与酒
情歌与酒 2020-12-12 20:11

Just to be clear: I do know that malloc and free are implemented in the C library, which usually allocates chunks of memory from the OS and does it

12条回答
  •  有刺的猬
    2020-12-12 20:47

    I'm only posting this as an answer not because it's the one you're hoping for, but because I believe it's the only plausibly correct one:

    It was probably deemed convenient originally, and it could not be improved thereafter.
    There is likely no convincing reason for it. (But I'll happily delete this if shown it's incorrect.)

    There would be benefits if it was possible: you could allocate a single large piece of memory whose size you knew beforehand, then free a little bit at a time -- as opposed to repeatedly allocating and freeing small chunks of memory. Currently tasks like this are not possible.


    To the many (many1!) of you who think passing the size is so ridiculous:

    May I refer you to C++'s design decision for the std::allocator::deallocate method?

    void deallocate(pointer p, size_type n);
    

    All n T objects in the area pointed to by p shall be destroyed prior to this call.
    n shall match the value passed to allocate to obtain this memory.

    I think you'll have a rather "interesting" time analyzing this design decision.


    As for operator delete, it turns out that the 2013 N3778 proposal ("C++ Sized Deallocation") is intended to fix that, too.


    1Just look at the comments under the original question to see how many people made hasty assertions such as "the asked for size is completely useless for the free call" to justify the lack of the size parameter.

提交回复
热议问题