10

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?

ire_and_curses
  • 68,372
  • 23
  • 116
  • 141
Werner Echezuria
  • 612
  • 1
  • 10
  • 23
  • 2
    The argument to `malloc()` is almost certainly wrong - you're allocating enough memory to store a `char *`, but assigning to a pointer that points to `char` (and there's no need to cast the return value of `malloc` in C, either). `str = malloc(N * sizeof *str);` is a better way to write that. – caf Aug 20 '09 at 12:32
  • As CAF said, you should never cast the return value of malloc(). See http://stackoverflow.com/questions/1565496/specifically-whats-dangerous-about-casting-the-result-of-malloc et al – Mawg says reinstate Monica May 04 '15 at 07:52

5 Answers5

13

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.

Matthew Iselin
  • 10,400
  • 4
  • 51
  • 62
  • 1
    Good answer (and question), I stumbled upon the same problem recently. One question: What if it's difficult to determine beforehand how much memory the function's return value needs? Then it would seem more natural to allocate in the function; otherwise you'd need some error handling in the function for the case that the supplied memory space is too small (e.g. for returning a string of variable length). – sleske Dec 31 '09 at 18:23
  • A variable length string could justify having memory allocated within the function. I would be very hesitant about such code in my own project however, and rather prefer to explicitly specify a maximum length that is chosen based on the context and requirements of the code. What sort of variable length strings are you talking about? They couldn't possibly be more than several KB/MB that could be pre-allocated? – Matthew Iselin Jan 01 '10 at 02:20
4

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.

2

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.

Alex Rodrigues
  • 2,567
  • 1
  • 14
  • 9
2

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.

sharptooth
  • 167,383
  • 100
  • 513
  • 979
2

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.

ezpz
  • 11,767
  • 6
  • 38
  • 39
  • 2
    Agreed, but what if it's difficult to decide beforehand how much space will be needed (e.g. dynamically creating a string to be returned). Then it would seem more natural (and simpler) for the function to allocate as much memory as it needs. What do you think? – sleske Dec 31 '09 at 18:25
  • A very good point. However, in reality, there will always be a known upper length to the sting, as it will have to fit into a database field, or on a screen or formatted output. Of course, it is wasteful to allocate 255 bytes when you might only need one, so it depends on what you are implementing. I wouldn’t worry too much in a Windows application, but an embedded system on an 8-bit micro is a different kettle of coloured horses. – Mawg says reinstate Monica May 04 '15 at 07:59