Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
176 views
in Technique[技术] by (71.8m points)

c - Using pointer after free()

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
",phead->module_id, phead->adc_id);

free(phead);

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

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

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

The output of this code is:

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

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

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...