且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

释放内存后我们如何访问指针?

更新时间:2023-02-02 21:14:33

你当然可以在调用 free(p) 后继续使用 p ,没有什么能阻止你.然而,结果将是完全未定义和不可预测的.它只能靠运气.这是一个常见的编程错误,称为免费使用后使用",它适用于许多程序字面上没有问题"——直到它引起问题.

You can certainly continue to use p after calling free(p) and nothing will stop you. However the results will be completely undefined and unpredictable. It works by luck only. This is a common programming error called "use after free" which works in many programs for literally years without "problems" -- until it causes a problem.

有一些工具可以很好地查找此类错误,例如 Valgrind.

There are tools which are quite good at finding such errors, such as Valgrind.