6

I have a function that allocates string and returns its pointer. When I use it directly in call of other function, do I need to free the memory?

For example:

char *getRow(){
     char *someString = (char*) malloc(sizeof(char) * 10);
     strcpy(someString , "asdqwezxc");
     return someString;
}

int main(){
     printf("%s", getRow());
}

What happens with memory allocated in that function? Is there any way to free it or do I need to store it to some variable before using it?

user10099
  • 1,345
  • 2
  • 17
  • 23
  • 3
    This formally leaks the allocated memory. In *this* code it doesn't matter because the program ends immediately thereafter, but it is not good practice. – dmckee --- ex-moderator kitten Nov 18 '12 at 04:08
  • That's bad practice, It'd be better to pass the pointer as a reference, so you can allocate and free the string outside the function, just like standard library does. – Toribio Nov 18 '12 at 04:08
  • If the allocation size is always static like in this example, you could always use a fixed-size buffer that you pass as a parameter to get row. Like a `char buf[10]; getRow(buf);` There's limited situations in which that can apply though, and then you have to be very mindful of the calling contract of getRow. (In other words, probably a bad idea for anything complex unless you have more constraints in place.) – Corbin Nov 18 '12 at 04:15
  • don't cast the return of `malloc` in C: http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc – Jens Gustedt Nov 18 '12 at 07:46
  • ok thanks, i'll just use references – user10099 Nov 18 '12 at 14:15
  • If you have "references" available then *this is not c*. – dmckee --- ex-moderator kitten Nov 19 '12 at 00:29

3 Answers3

8

Even if you have returned from the function, the memory is not deallocated unless you explicitly do so. So you must store the return value and call free.

int main(){
    char* str = getRow();
    printf("%s", str);
    free(str);
}
Sidharth Mudgal
  • 4,234
  • 19
  • 25
  • ok thanks, i was just hoping that there is some way, because it's much comfortable calling function like this printf("%s", getRow()); instead of storing it and then using, especially when you need to call that function more times with different parameters – user10099 Nov 18 '12 at 04:30
  • but how would I return it? local variables die after function ends, dont they? – user10099 Nov 18 '12 at 05:01
1

You need to store it in a variable, use it, then free it. If you don't free it you get a memory leak.

David Buck
  • 2,847
  • 15
  • 16
0

Yes, you need. malloc allocate memory from heap which you need to free it explicitly. Variable such as char *someString is allocated from stack which will be freed when the function returns. I think you misunderstand stack and heap.

Look at this what-and-where-are-the-stack-and-heap

Community
  • 1
  • 1
louxiu
  • 2,830
  • 3
  • 28
  • 42