C - free()之后会发生什么?

Mil*_*les 7 c struct pointers

我有这个结构类型,我malloc为,并在我释放后,指针仍然指向我分配的数据.这只是因为指针指向可以释放但尚未重新分配的内存吗?

#include <stdio.h>

typedef struct Katze {
    int value;
} Katze;

int main () {
    Katze *mew = malloc(sizeof(Katze));
    mew->value = 8910;
    free(mew);
    printf("mew: %i\n", mew->value); // why does this still say "mew: 8910"?
}
Run Code Online (Sandbox Code Playgroud)

Lee*_*ker 14

释放的记忆不再属于你了.但这并不意味着它会以任何方式消失或改变.为什么你的程序会烦恼?这将浪费时间.它可能只是将内存标记为可供后续malloc()s 使用,就是这样.或者它可能不会.使用不属于您的内存可能会执行任何操作:返回错误的值,崩溃,返回正确的值或运行飞行模拟器游戏.这不是你的; 不要乱用它,你永远不必担心它会做什么.

  • 我希望*我的*UB程序可以运行飞行模拟游戏.*我的*UB程序似乎只是给我鼻腔恶魔...... (4认同)