Using pointer after free()

c, linux

Solution

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

Problem

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); } ``` 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?

Original source

Related problems