简体   繁体   English

为什么我可以释放内存两次,但是在不同情况下却不能?

[英]Why can I free memory twice, but can't in different situations?

This is the code I have currently. 这是我目前拥有的代码。

int main() {
    double *t, *k;
    Item *a = calloc(1, sizeof(Item));
    a->w = malloc(sizeof(double));
    t = a->w;
    k = t;
    free(a->w);
    free(a);
    free(k);
    return 0;
}

In this example, I was able to compile and run without getting any explicit errors. 在此示例中,我能够编译并运行而没有任何显式错误。 However if I free the pointer, k, before the structure, a, is freed, then I receive a double free/heap corruption error. 但是,如果我在释放结构a之前释放了指针k,那么我会收到一个双重的free / heap损坏错误。

free(a->w);
free(k);
free(a);

Additionally, I receive the same error if I do: 此外,如果执行以下操作,则会收到相同的错误:

free(k);
free(a->w);
free(a);

Why is it that I can free the pointer, k after the structure has been freed without any explicit errors, but I cannot free the memory k is pointing twice until the structure a is freed? 为什么在释放结构k之后没有任何显式错误的情况下我可以释放指针k,但是在释放结构a之前我不能释放内存k指向两次?

This is an example of Undefined behavior . 这是未定义行为的示例。 This means anything can happen, such as appearing to work, crashing immediately, crashing at some point later, or strange unexpected behavior, or the often mentioned nasal demons . 这意味着任何事情都可能发生,例如看起来正常工作,立即崩溃,稍后崩溃,奇怪的意外行为或经常提到的鼻恶魔

From the man page : 手册页

free() frees the memory space pointed to by ptr, which must have been returned by a previous call to malloc(), calloc() or realloc(). free()释放ptr指向的内存空间,该内存空间必须已由先前对malloc(),calloc()或realloc()的调用返回。 Otherwise, or if free(ptr) has already been called before, undefined behaviour occurs . 否则, 或者如果之前已经调用过free(ptr),则会发生未定义的行为 If ptr is NULL, no operation is performed. 如果ptr为NULL,则不执行任何操作。

So triggering a double-free error may occur but is not required. 因此可能会触发双重释放错误,但这不是必需的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM