Reusing freed pointers in C

后端 未结 4 1915
臣服心动
臣服心动 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:09

    1. Since the original pointer now points into allocated space once more, it is possible to use it. However, it is a bad idea to do so; the code that allocated the memory thinks it has control of it and will be upset if the code using the old pointer modifies the data. Also, it is likely that the new code is storing different types of data from what the old pointer expects, so the code using the old pointer won't understand what's going on.

      In your example, reusing the pointer variable is a non-problem. The value returned by the second malloc() may be the same as was returned by the first, or it may be different, but (even without the assignment of NULL) reusing the pointer like that is fine (as long as you subsequently free the second allocation).

    2. If the space is freed, it is possible (albeit rather unlikely) that the space was unmapped by the O/S and is no longer a part of the valid addresses available to your program. It is more likely that confusion over what the data means will cause the program to crash than that the space was returned to the O/S, but either is possible.

    Summary: don't use old pointer values to access re-allocated memory — it will lead to unhappiness.

提交回复
热议问题