Article From:

Original address:

  In most systems, the C applet will absorb all free memory.


Before we talk about malloc (0), let’s take a look at the simpler case of malloc (1).

   There is a new interesting C program question about malloc: “using a pointer to dynamically allocate memory, how can we decide on how many bytes (byte) is it pointing to? “The answer is frustrating.” you can’t decide. ” But when you call free in the same pointer, memory allocationKnowing how large the block is, it is stored somewhere in the computer. This area is usually allocated adjacent memory, and any other specific data that the distributor needs to implement.

  In the implementation of the universal dlmalloc, this overhead in 4~16 bytes is added to a request, depending on how the library is precompiled and whether the pointer is 32 or 64 bits. The 8 byte is a reasonable guess for the 64 bit system.

  The worse thing is that the smallest block can be returned by malloc. Alignment is one of the reasons. If an integer size space is added to each block in secret, then it will not be meaningful for assigning a smaller block than integer. But there is another reason: when a block is free,It will be tracked in some way. Maybe it enters a list, or enters a tree, or something more interesting. In any case, pointers or other data will have to go somewhere, and it is a free choice in the newly released blocks.

  In dlmalloc, the smallest allowed size in a 64 bit system is 32 bits. Back to the problem of malloc (1), the overhead of 8 bytes is added to the single bytes we need, and together it is smaller than the smallest 32, so our answer is: MallOC (1) assigns 32 bytes.

  Now we are able to tackle the problem of distributing 0 bytes. It proves that the facts will have a stupid debate, and it has not yet been solved, so the technical allocation of 0 bytes is a specific realization behavior. One side thinks that malloc (0) should return a null pointer and complete it. It executes if you do not introduceAn empty return value service is double responsibility. It also means “out of memory” or “you don’t need any memory.”

  A more general form is that malloc (0) returns a special pointer. You should not refer to that pointer because it is conceptually pointing to 0 bytes. From the discussion above, we know that at least dlmalloc will always allocate a 32 byte block in the 64 – bit system, so this is the end.Answer: it needs 32 bytes to satisfy your requests for no memory.

Leave a Reply

Your email address will not be published. Required fields are marked *