How does free know how much to free?

后端 未结 11 2129
情话喂你
情话喂你 2020-11-22 03:28

In C programming, you can pass any kind of pointer you like as an argument to free, how does it know the size of the allocated memory to free? Whenever I pass a pointer to s

相关标签:
11条回答
  • 2020-11-22 03:56

    On a related note GLib library has memory allocation functions which do not save implicit size - and then you just pass the size parameter to free. This can eliminate part of the overhead.

    0 讨论(0)
  • 2020-11-22 03:59

    The original technique was to allocate a slightly larger block and store the size at the beginning, then give the application the rest of the blog. The extra space holds a size and possibly links to thread the free blocks together for reuse.

    There are certain issues with those tricks, however, such as poor cache and memory management behavior. Using memory right in the block tends to page things in unnecessarily and it also creates dirty pages which complicate sharing and copy-on-write.

    So a more advanced technique is to keep a separate directory. Exotic approaches have also been developed where areas of memory use the same power-of-two sizes.

    In general, the answer is: a separate data structure is allocated to keep state.

    0 讨论(0)
  • 2020-11-22 04:07

    To answer the second half of your question: yes, you can, and a fairly common pattern in C is the following:

    typedef struct {
        size_t numElements
        int elements[1]; /* but enough space malloced for numElements at runtime */
    } IntArray_t;
    
    #define SIZE 10
    IntArray_t* myArray = malloc(sizeof(intArray_t) + SIZE * sizeof(int));
    myArray->numElements = SIZE;
    
    0 讨论(0)
  • 2020-11-22 04:09

    From the comp.lang.c FAQ list: How does free know how many bytes to free?

    The malloc/free implementation remembers the size of each block as it is allocated, so it is not necessary to remind it of the size when freeing. (Typically, the size is stored adjacent to the allocated block, which is why things usually break badly if the bounds of the allocated block are even slightly overstepped)

    0 讨论(0)
  • 2020-11-22 04:11

    malloc() and free() are system/compiler dependent so it's hard to give a specific answer.

    More information on this other question.

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