使用指针免费后() [英] Using pointer after free()

查看:152
本文介绍了使用指针免费后()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的测试中,我发现,它有可能释放后使用指针()。我有以下的code:

During my tests, I have found that it is possible to use pointer after free(). I have the following code:

typedef struct{

    int module_id;
    int adc_id;
    struct config_line * pnext;

} config_line;
config_line * create_list()
{

config_line * phead = (config_line *) malloc(sizeof(config_line));
phead->pnext=NULL;
phead->module_id = 1;
phead->adc_id = 2;

printf("module_id=%d adc_id=%d\n",phead->module_id, phead->adc_id);

free(phead);

printf("module_id=%d adc_id=%d\n",phead->module_id, phead->adc_id);

phead->module_id = 2;
phead->adc_id = 5;

printf("module_id=%d adc_id=%d\n",phead->module_id, phead->adc_id);
}

这code的输出是:

module_id=1 adc_id=2
module_id=0 adc_id=2
module_id=2 adc_id=5

后为什么免费(PHEAD)我可以访问(读取和写入)的指针?为什么没有分割的错吗?

Why after free(phead) I can get access (read and write) to pointer? Why there is not segmentation fault?

推荐答案

由于使用无效的指针调用未定义的行为。这意味着,该行为是...好... 不确定的。这不是不得不以崩溃。

Because using an invalid pointer invokes undefined behavior. And that means that the behavior is... well... undefined. It's not obliged to crash.

这篇关于使用指针免费后()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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