我正在使用2D数组,我需要按照所示分配它:
char ** buf; //global var
void allocate()
{
buf = (char **) malloc (10 * sizeof (char*));
char * data = (char *) calloc (1, 1000);
int i;
for(i=0; i<10; i++)
buf[i] = &(data[i*100]);
}
int main()
{
allocate();
//something goes here
free(buf[0]);
free(buf);
return 0;
}
现在要释放数组,因为我无法访问 main()中的变量' data ',我无法执行 free(data),因此我做 free(buf [0]),假设我释放了整个1000个元素的数组。这是正确的方法吗? free(buf [0])是否释放整个'data'数组?
(将buf的每个元素作为buf [i] = malloc(100)进行malloc很方便,但我不能这样做,因为我必须首先调用一个大块。)
提前致谢。
答案 0 :(得分:4)
此代码是正确的。根据定义,buf[0]
的值为&(data[0])
,data
。这将释放所有分配的内存。
请注意,如果您真的想要释放一个缓冲区,可以设置:
offset = 10*sizeof(char*);
buf = calloc(10*100+offset);
并在循环中执行:
buf[i] = buf + offset + i*100;
答案 1 :(得分:3)
这有点不寻常,但它是正确的。你做了两次分配;你做两个自由。然后你释放分配的指针。一切都应该干净。
您是否在计划上运行了valgrind
?
答案 2 :(得分:3)
Valgrind同意你的看法。这是正确的,因为buf [0]保存指向calloc内存块的HEAD的指针。
valgrind ./temp
==15404== Memcheck, a memory error detector
==15404== Copyright (C) 2002-2009, and GNU GPL'd, by Julian Seward et al.
==15404== Using Valgrind-3.6.0.SVN-Debian and LibVEX; rerun with -h for copyright info
==15404== Command: ./temp
==15404==
==15404==
==15404== HEAP SUMMARY:
==15404== in use at exit: 0 bytes in 0 blocks
==15404== total heap usage: 2 allocs, 2 frees, 1,040 bytes allocated
==15404==
==15404== All heap blocks were freed -- no leaks are possible
==15404==
==15404== For counts of detected and suppressed errors, rerun with: -v
==15404== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 12 from 7)