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 some function, I have to also pass the size (ie an array of 10 elements needs to receive 10 as a parameter to know the size of the array), but I do not have to pass the size to the free function. Why not, and can I use this same technique in my own functions to save me from needing to cart around the extra variable of the array's length?


当前回答

要回答第二个问题,是的,您可以(某种程度上)使用与malloc()相同的技术 通过简单地将每个数组中的第一个单元格分配给数组的大小。 这样就可以在不发送额外size参数的情况下发送数组。

其他回答

当您调用malloc时,堆管理器将属于已分配块的内存量存储在某处。

我从来没有实现一个自己,但我猜在前面的内存分配块可能包含元信息。

回答你问题的后半部分:是的,你可以,在C语言中一个相当常见的模式如下:

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;

与此相关的是,GLib库具有不保存隐式大小的内存分配函数——然后您只需将size参数传递给free即可。这可以减少部分开销。

Malloc()和free()依赖于系统/编译器,所以很难给出一个具体的答案。

更多关于这个问题的信息。

来自comp.lang.c常见问题列表:free如何知道释放多少字节?

malloc/free实现在分配每个块时记住它的大小,因此在释放时不需要提醒它大小。(通常,大小存储在已分配块的相邻位置,这就是为什么如果已分配块的边界稍有超出,情况通常会很糟糕)