简体   繁体   English

在函数内部使用malloc并返回本地指针

[英]Using malloc inside a function and return local pointer

Is there any problem in doing something like this in C 在C中做这样的事情有什么问题吗

char* wrap(char *inp) {
    char *newstr;
    newstr = (char *)malloc( sizeof(char) * 4);
    newstr[0] = 'A';
    newstr[1] = inp[0];
    newstr[2] = 'B';
    newstr[3] = '\0';
    return newstr;
}

Basically I want to know that is there problem in using malloc inside a function and returning local variable. 基本上我想知道在函数内部使用malloc并返回局部变量存在问题。

You're not returning a local variable; 你没有返回一个局部变量; you're returning the value stored in a local variable. 您传回存储在一个局部变量的

This code is fine (although the cast on malloc is unnecessary); 这段代码没问题(尽管malloc上的malloc是不必要的); it's a somewhat common pattern to allocate memory in one function and free it in another. 在一个函数中分配内存并在另一个函数中释放它是一种有点常见的模式。

This is perfectly fine as long as you call free() somewhere to avoid memory leaks. 只要你在某个地方调用free()以避免内存泄漏,这就完全没问题了。 Part of your program design should be defining the "owner" of each pointer. 程序设计的一部分应该是定义每个指针的“所有者”。 Such ownership can be transferred, so you should keep track of the owner throughout the lifetime of the pointer. 这种所有权可以转移,因此您应该在指针的整个生命周期内跟踪所有者。 The owner at the time the pointer becomes unused should be responsible for calling free() . 指针变为未使用时的所有者应负责调用free()

That's perfect, as long as you're super sure the caller is going to call free to avoid memory leaks .. That's not a big issue on small programs, but when the program gets complex, believe me, you'll be concerned about much more things than freeing a pointer from a supposed-to-be self-contained function .. 这是完美的, 只要你确定调用者可以免费调用以避免内存泄漏..这对小程序来说不是一个大问题,但是当程序变得复杂时,相信我,你会关心很多比从一个假定的自包含函数释放指针更多的东西..

But (hands down), there's a much more satisfying solution to this that the standard C Library itself uses. 但是(向下),有一个更令人满意的解决方案,标准C库本身使用。 Use a Buffer ! 使用缓冲区! (Claps, Claps) (拍手,拍手)

You know, there is a reason the fgets function for example requires you to provide a character pointer as the first argument, so that it can write to it rather than returning a malloc'd pointer .. 你知道,有一个原因,例如fgets函数要求你提供一个字符指针作为第一个参数,这样它就可以写入它而不是返回一个malloc指针。

For example .. 例如 ..

#include <ctype.h>
#include <string.h>

void toLower(char *buf, const char *s) {
    for(int i = 0; s[i]; ++i)
        buf[i] = tolower(s[i]);
}
int main(int argc, const char ** argv) {
    const char *s = "ThAt'S a BiG sTrIng";
    char lower_version[strlen(s)];
    toLower(lower_version, s);
    printf("Original Version: %s\nLower Version: %s\n\tTada !\n", s, lower_version);
}

That way, you don't have to worry how you're going to handle the variable in later uses .. 这样,您不必担心在以后的使用中如何处理变量。
You're leaving this problem to the function caller to deal with. 您将此问题留给函数调用者来处理。

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

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