记住这个简单的原则:“总是在你分配它的同一级别释放内存”.换句话说,函数永远不应该尝试释放它本身没有分配的内存.一个简短的例子来阐明这一点:
#include "graphics.h"
// The graphics API will get a Canvas object for us. This may be newly allocated
// or one from a pool of pre-allocated objects.
Canvas* canvas = graphics_get_canvas ();
// If draw_image () frees canvas, that violates the above principle.
// The behavior of the program will be unspecified. So, just draw the image
// and return.
draw_image (canvas);
// This is also a violation.
// free (canvas) ;
// The right thing to do is to give back the Canvas object to the graphics API
// so that it is freed at the same 'level' where it was allocated.
graphics_return_canvas (canvas);
请注意,该函数未命名为graphics_free_canvas()或类似的东西,因为API可以选择释放它或通过将其返回池来重用它.关键是,假设我们没有创建的资源的所有权是一种非常糟糕的编程习惯,除非我们另外特别说明.