1

这种行为记录在哪里(如果有的话)?

当您在 C 中在块的中间声明一个指针时,它可能处于错误状态(指向不可用的内存)并且您不能使用标准if (a) free(a)来释放它。

想到的最简单的程序是

#include <stdlib.h>
int main(int argc, char *argv[]){
    if(argc > 1) goto END;
    char *a = NULL;
    a = calloc(1,1);
END:
    if(a) free(a);
}

运行不带参数的程序,它工作正常,如果你用至少一个参数运行它,它可能会出现如下错误:(对我来说)令人惊讶的是,如果你用 clang 编译它,它可能会工作(在我的 OS X 上它确实,但在 NetBSD 上却没有)。如果你使用 gcc,它总是返回一个

malloc: *** error for object 0x7fff5fc01052: pointer being freed was not allocated

请注意,在块头声明的同一程序是正确的。

编辑:请注意,问题是关于文档的。我意识到做我描述的事情是不安全的,但我发现没有明确显示它的地方。

4

1 回答 1

3

The "pattern"

if(a) free(a);

is certainly not standard, or at least it shouldn't be. It's safe to pass NULL to free(), so the if adds nothing.

I would expect the value of a to be undefined (not likely to be NULL) if you jump past the initialization, which makes perfect sense to me. This is really hairy code, don't do this.

It could be argued that the existance of the goto and label imply a scope that isn't implemented, and there's no reason at all that the free(a); statement is after the label (outside the "invisible" scope where a is defined).

于 2013-04-18T09:59:16.813 回答