如果自由()知道我的数组的长度,我为什么不能要求它在我自己的code? [英] If free() knows the length of my array, why can't I ask for it in my own code?
问题描述
我知道它是动态分配的数组的长度传递给操纵它们的功能一个共同的约定:
I know that it's a common convention to pass the length of dynamically allocated arrays to functions that manipulate them:
void initializeAndFree(int* anArray, size_t length);
int main(){
size_t arrayLength = 0;
scanf("%d", &arrayLength);
int* myArray = (int*)malloc(sizeof(int)*arrayLength);
initializeAndFree(myArray, arrayLength);
}
void initializeAndFree(int* anArray, size_t length){
int i = 0;
for (i = 0; i < length; i++) {
anArray[i] = 0;
}
free(anArray);
}
但如果没有办法,我从一个指针获得分配的内存的长度,请问免费()
自动地知道该怎么当所有我释放'M赋予它是非常相同的指针?为什么我不能得到的神奇,作为一个C程序员?
but if there's no way for me to get the length of the allocated memory from a pointer, how does free()
"automagically" know what to deallocate when all I'm giving it is the very same pointer? Why can't I get in on the magic, as a C programmer?
哪里免费()
得到它的自由(HAR-HAR)的知识?
Where does free()
get its free (har-har) knowledge from?
推荐答案
此外Klatchko的正确的点,该标准没有规定的,真正的malloc /免费实现通常分配更多的空间,然后你问。例如。如果你问12个字节它可以提供16条(见内存分配,其中指出,16是常见大小)。所以,它并不需要知道你问12个字节,只是它的给你的一个16字节的块。
Besides Klatchko's correct point that the standard does not provide for it, real malloc/free implementations often allocate more space then you ask for. E.g. if you ask for 12 bytes it may provide 16 (see A Memory Allocator, which notes that 16 is a common size). So it doesn't need to know you asked for 12 bytes, just that it gave you a 16-byte chunk.
这篇关于如果自由()知道我的数组的长度,我为什么不能要求它在我自己的code?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!