将char*作为参数传递给函数时,被调用函数是否应该对该字符串执行free?否则,数据将"丢失",程序将泄漏数据.或者编译器以特殊方式处理char*以避免每个人不得不一直处于空闲状态并自动删除它超出范围?我将"字符串"传递给函数,因此不将实例传递给已存在的char*.或者应该使用char []代替?只是觉得为参数输入设置一个固定的限制是如此愚蠢.
Vij*_*hew 15
记住这个简单的原则:"总是在你分配它的同一级别释放内存".换句话说,函数永远不应该尝试释放它本身没有分配的内存.一个简短的例子来阐明这一点:
#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);
Run Code Online (Sandbox Code Playgroud)
请注意,该函数未命名graphics_free_canvas ()或类似,因为API可以选择释放它或通过将其返回到池来重用它.关键是,假设我们没有创建的资源的所有权是一种非常糟糕的编程习惯,除非我们另外特别说明.
听起来你问的是这个用法:
void foo(char* str);
foo("test string");
Run Code Online (Sandbox Code Playgroud)
这是一个特例; "test string"是存储在可执行文件中的字符串表中的常量字符串,不需要释放.foo实际上应该用a const char*来说明这一点,并且char*在C++中不允许将字符串文字存储在非常量s中
函数是否应该执行free取决于谁拥有该字符串.此代码完全有效,不会导致任何内存泄漏:
int main()
{
char* s = malloc(.....);
f(s);
free(s);
}
Run Code Online (Sandbox Code Playgroud)
在free可以内部功能来执行f,以及如果需要字符串的所有权.但请注意,这是危险的,因为您假设传递给函数的字符串f始终在堆上使用malloc或相关函数分配.如果用户将指针传递给堆栈上分配的字符串,则程序将表现得不可预测.
一般来说,编译器不对字符串的内存管理进行任何特殊处理.从编译器的角度来看,它只是一堆字符.
| 归档时间: |
|
| 查看次数: |
520 次 |
| 最近记录: |