C-free()之后会发生什么事情? [英] C - What Happens To Memory After free()?

查看:110
本文介绍了C-free()之后会发生什么事情?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有为我分配的这种结构类型,释放它后,指针仍然指向我分配的数据.仅仅是因为指针指向的是空闲但尚未重新分配的内存吗?

I have this struct type that I malloc for, and after I free it the pointer still points to the data I assigned. Is that just because the pointer is pointing to memory that is free but hasn't been reallocated yet?

#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"?
}

推荐答案

已释放的内存不再属于您.但这并不意味着它会以任何方式消失或改变.为什么您的程序会打扰?那样会浪费时间.它可能只是将内存标记为可供以后的malloc()使用,仅此而已.否则可能不会.使用不属于您的内存可能会做任何事情:返回错误的值,崩溃,返回正确的值或运行飞行模拟器游戏.不是你的别惹它,您永远不必担心它会做什么.

Freed memory doesn't belong to you anymore. But that doesn't mean it disappears or gets changed in any way. Why would your program bother? It would be a waste of time. It probably just marks the memory as available for use by subsequent malloc()s, and that's it. Or it might not. Using memory that doesn't belong to you might do anything: return wrong values, crash, return right values, or run a flight simulator game. It's not yours; don't mess with it and you'll never have to worry about what it might do.

这篇关于C-free()之后会发生什么事情?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆