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()和free()依赖于系统/编译器,所以很难给出一个具体的答案。

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

其他回答

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

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

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

回答你问题的后半部分:是的,你可以,在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;

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

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

在调用malloc()时,指定要分配的内存量。实际使用的内存量略大于此值,并包括额外的信息,记录(至少)块的大小。你不能(可靠地)访问其他信息-你也不应该:-)。

当调用free()时,它只是查看额外的信息,以确定块有多大。