Monday, July 27, 2009

What happens to the memory at the end of a function call in C?

I'm trying to figure out if I have to actually free the memory for a string that I'm using until the end of a function in a C program and was wondering if when the function ends all the memory allocated for strings, ints, and other stuff in the method is reclaimed automatically or if it's lost in a memory leak.

What happens to the memory at the end of a function call in C?
It depends on the class of varibales your are using. All variables contains garbage values excpt static varibales.
Reply:Typically, you only need to free memory that you've acquired via the malloc() call. If you have a string in a function, it's a literal and is just a null terminated string in static memory. You don't need to deal with it. Arguments to the function are allocated on the stack and are claimed with the function ends.
Reply:Your question is a bit unclear since it doesn't say how you allocated the memory for the string.





Was it an argument passed in? If so, someone else (the caller) allocated the memory and should worry about freeing it.





Did you declare it as an automatic array of characters in the function, e.g.


int function(){


char mystring[100];


...


In that case, the memory is on the stack and will be automatically freed on return.





Did you explicitly allocate the memory, e.g.


int function(){


char *mystring = (char *)malloc(100);


...


In that case, you must free the memory before returning. Unless, of course, you're returning a pointer to the allocated memory, in which case it's the caller's responsibility to free.


No comments:

Post a Comment