Reusing freed pointers in C

后端 未结 4 1921
臣服心动
臣服心动 2020-12-16 14:34

There are many questions on this website regarding freeing pointers after use and, further, setting them to NULL. Arguments are fierce and the topic is seemingly divided equ

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-16 15:12

    Given a freed pointer, what is keeping you from reassiging that pointer to a new memory location?

    Technically, nothing. You do not even need to set ptr = NULL in between of freeing and re-assigning the pointer. When freeing and re-assigning are separated by other lines of code, however, setting the pointer to NULL may improve readability slightly.

    Why would writing to a memory block that was previously freed, that still has the original pointer to it, cause the program to crash?

    Simply holding a pointer to a block of memory accessible through another pointer is absolutely OK, as long as your program does not try dereferencing that pointer. Unfortunately, even if you dereference the freed pointer, it would not necessarily cause your program to crash: more often than not, such behavior would go unnoticed. It remains an undefined behavior, though. Another part of your program may have written data incompatible with what you expect, in which case you will see bugs that are extremely hard to find or explain.

提交回复
热议问题