Is free() zeroing out memory?

后端 未结 7 1487
庸人自扰
庸人自扰 2020-12-03 06:24

Until today I lived in belief that calling free() on memory space releases it for further allocation without any other modifications. Especially, considering th

相关标签:
7条回答
  • 2020-12-03 07:23

    There is another pitfall you might have not known actually, here:

    free(pointer);
    
    printf("After free(): %p \n", pointer); 
    

    Even just reading the value of pointer after you free it is undefined behaviour, because the pointer becomes indeterminate.

    Of course dereferencing the freed pointer - like in below example - is also not allowed:

    free(pointer);
    
    printf("After free(): %p, %d\n", pointer, *pointer);
    

    ps. In general when printing address with %p (like in printf) cast it to (void*), e.g. (void*)pointer - otherwise you get undefined behaviour also

    0 讨论(0)
提交回复
热议问题