简体   繁体   English

返回已分配的变量

[英]Return an allocated variable

I know we should free any variable allocated with malloc, but what if I return it in a function? 我知道我们应该释放任何用malloc分配的变量,但如果我在函数中返回它会怎么样? Something like this: 像这样的东西:

char *somefunction(int somearg){
    char *str;

    str=(char *)malloc(sizeof(char *));

    //some code

    return str;
}

Should I free str? 我应该免费吗? How could I do that? 我怎么能这样做?

You have two options: one, pass a char* to somefunction and use that instead of allocating within somefunction, or two, free the return value later on. 你有两个选择:一个,将char *传递给某个函数并使用它而不是在某个函数中分配,或者两个,稍后释放返回值。

The first option: 第一种选择:

char *somefunction(char *str, int somearg){

    //some code

    return str;
}

// Elsewhere...
char *str = (char *) malloc....;
somefunction(str, 123);
// Code...
free(str);

The second option: 第二种选择:

char *somestr = somefunction(123);
// Do something...
free(somestr);

I personally suggest the first option, as it's a little easier to avoid leaking memory when it's not being allocated within arbitary functions. 我个人建议使用第一个选项,因为当它没有在仲裁函数中分配时,更容易避免泄漏内存。

You free it when you have finished with it. 完成后你可以释放它。 There is no rule that says that the free() that matches a malloc() must be in the same function. 没有规则说与malloc()匹配的free()必须在同一个函数中。

You should free all the allocated space but if you return its because you will use those memory space in other parts of the program, so after you use it you should free. 你应该释放所有分配的空间,但如果你返回它,因为你将在程序的其他部分使用这些内存空间,所以在你使用之后你应该释放。 See every place in the code that calls the function and free the space after you use the returned value. 查看调用该函数的代码中的每个位置,并在使用返回的值后释放空间。

If you intend to return the address of the block you should not free() the block but instead rely on the calling code to free() it later. 如果你打算返回块的地址,你不应该释放()块,而是依赖于调用代码以后释放()它。 This is called onwership passing. 这叫做onwership传递。

If you free it in the function and return the pointer the calling code will run into undefined behavior trying to access the already freed block. 如果在函数中释放它并返回指针,则调用代码将在尝试访问已释放的块时遇到未定义的行为。

This is a practice for some existing functions ( strdup() , for instance) but is generally a bad idea. 这是一些现有函数(例如strdup()的实践,但通常是个坏主意。 Requiring that a user be aware of what happens inside a function call is a bad requirement - think how many functions you use who's internals are hidden from you. 要求用户了解函数调用内部发生的事情是一个不好的要求 - 想想你使用了多少函数是谁的内部隐藏对你。 Generally speaking, you will want to have a user pass in a buffer and size instead of allocating memory for them. 一般来说,您需要让用户传入缓冲区和大小,而不是为它们分配内存。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM