【发布时间】:2011-12-27 11:16:07
【问题描述】:
我正在努力用 c 语言处理 malloc - 特别是当它需要 free()'d 时。我在 gcc 中遇到奇怪的错误,例如:
... free(): invalid next size (fast): ...
当我尝试释放 char 指针时。例如,从输入文件中读取时,在执行以下操作时会在某些行崩溃:
FILE *f = fopen(file,"r");
char x[256];
while(1) {
if(fgets(x,sizeof x,f)==NULL) break;
char *tmp = some_function_return_char_pointer(x); //OR malloc(nbytes);
// do some stuff
free(tmp); // this is where I get the error, but only sometimes
}
我检查了一些明显的东西,例如 x 为 NULL,但它不是;它只是在随机线上崩溃。
但我真正的问题是 - 我什么时候需要使用 free()?或者,可能更正确的是,我什么时候不应该免费使用?如果 malloc 在函数中,我返回使用 malloc() 的 var 怎么办?在 for 或 while 循环中呢? struct 数组的 malloc-ing 是否与 string/char 指针具有相同的规则?
我从 gcc 中程序崩溃时遇到的错误中收集到,我只是不了解 malloc 和 free。我在 Google 上度过了美好的时光,但我仍在碰壁。有没有找到好的资源?我所看到的一切都表明,每当我使用 malloc 时,我都需要使用 free。但后来我尝试了,我的程序崩溃了。所以也许它会根据变量的范围而有所不同?当在循环内部声明变量时,C 是否会在循环结束时释放内存?在函数结束时?
所以:
for(i=0;i<100;i++) char *x=malloc(n); // no need to use free(x)?
但是:
char *x;
for(i=0;i<100;i++) {
x=malloc(n);
free(x); //must do this, since scope of x greater than loop?
}
是吗?
希望我是有道理的......
【问题讨论】:
-
任何你 malloc() 的东西,当你不再需要使用它时,你释放(一次)。
-
你在 malloc'ing 零字节...? bytes.com/topic/c/answers/578467-what-malloc-0-should-returns 编辑: 刚刚意识到这无关紧要,因为无论如何你仍然可以
free(...)指针。