简体   繁体   中英

Return an allocated variable

I know we should free any variable allocated with malloc, but what if I return it in a function? 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.

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.

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.

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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