Werner Echezuria
Werner Echezuria

Reputation: 622

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?

Upvotes: 11

Views: 2332

Answers (5)

ezpz
ezpz

Reputation: 12027

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.

Upvotes: 2

anon
anon

Reputation:

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.

Upvotes: 4

sharptooth
sharptooth

Reputation: 170489

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.

Upvotes: 2

Alex Rodrigues
Alex Rodrigues

Reputation: 2707

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.

Upvotes: 2

Matthew Iselin
Matthew Iselin

Reputation: 10670

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.

Upvotes: 13

Related Questions