c语言char 函数参数,char *作为C中函数的参数

记住这个简单的原则:“总是在你分配它的同一级别释放内存”.换句话说,函数永远不应该尝试释放它本身没有分配的内存.一个简短的例子来阐明这一点:

#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可以选择释放它或通过将其返回池来重用它.关键是,假设我们没有创建的资源的所有权是一种非常糟糕的编程习惯,除非我们另外特别说明.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值