• C

How to free the memory allocated in the Local functions after the control returns to main program in C langugage

ex:
int main()
{
 fun();
}

void fun()
{
  char *str;
  int n;
  str = (char *) malloc(100);
  n = strlen(str);
  //some operations.
  return;
}
I wanted to know how & when to free the str.
will it be possible to free when the control goes back to main program.
Kindly help me.
netqueriesAsked:
Who is Participating?

Improve company productivity with a Business Account.Sign Up

x
 
sunnycoderConnect With a Mentor Commented:
Hi netqueries,

It is possible to free the memory assigned to str in main ... but for that you need the address of the memory assigned to be passed back to main ....

General rule of thumb is to free the memory when you do not need it anymore ...

In the example you posted, it seems that you do not have to use that memory outside fun .... Thus after completing all operations in fun() you can add a line free (str);

if you need to access that memory in main, return str to main and free it in main

ex:
int main()
{
 char * a = fun();
 free (a);
}

char * fun()
{
  char *str;
  int n;
  str = (char *) malloc(100);
  n = strlen(str);
  //some operations.
  return (str);
}

Sunnycoder
0
 
PerryDKCommented:
In generall it is bad programming practice to call a function and to expect the caller of the function to free the memory associated with the function.

What you should do in 99.9% of circumstances is pass a pointer to the function such as

void fun(char* str)
{
  //caller of this function should guarentee that str is at least of size 100
  //do some operatons
  //modify str
}

int main()
{
  char* str = (char*)malloc(100);
  fun(str);
  //use str
  free(str);
}
0
 
stefan73Commented:
Hi netqueries,
> str = (char *) malloc(100);
>   n = strlen(str);

Not good - what you get from malloc is not initialized.

BTW: If you know that the amount of memory is limited (it fits on the stack), you can use alloca() instead of malloc(). The memory will be freed automatically when the function returns.

Cheers,
Stefan
0
Build your data science skills into a career

Are you ready to take your data science career to the next step, or break into data science? With Springboard’s Data Science Career Track, you’ll master data science topics, have personalized career guidance, weekly calls with a data science expert, and a job guarantee.

 
stefan73Commented:
netqueries,

It's one of the problems of C that you don't have a "final" section which gets executed in every case. With your function it's simple, as you have only one return point:

oid fun()
{
  char *str;
  int n;
  str = (char *) malloc(100);
  n = strlen(str);
  //some operations.
  free(str);
  return;
}

But imagine a routine which has dozens of return points, some with implicit return (like via error checking macro, assert or exit). It gets messy quickly. Memory is returned to the system when the process ends, but not all ressources (think IPC!) are this grateful.

This is one of the few places where a goto can be appropriate *shudder*...

Stefan
0
 
ankuratvbCommented:
Another way to do this is use the pointer as a global variable:
char *str;

Now u can free memory allocated to str anywhere u want.
Here,using the pointer as global doesnt take up too much memory as its only a pointer(size is 2 bytes or 4 for a far ptr)

int main()
{
fun();
//free(str); u can do this here
}

void fun()
{
 int n;
 str = (char *) malloc(100);
 n = strlen(str);
 //some operations.
//free(str); u can do this here
 return;
}
0
 
sunnycoderCommented:
you can use atexit() or on_exit() to register function(s) which you wish to call upon exit

You will do fine with that unless you decide to call _exit instead of exit
0
 
ankuratvbCommented:
Hi stefan,

Is alloca() part of the standard library or do u need a specific library?
I don't have it on my compiler(TC ver3.0)
0
 
stefan73Commented:
ankuratvb,
alloca is defined in stdlib.h on my Solaris here.

Stefan
0
 
ankuratvbCommented:
I guess the only reason(i think) the OP would want to free the mem. allocated in a local function when control is passed back to main() is if he wanted to modify,access the memory allocated or free it according to the value of some flag calc. by some processing logic.

Then ,u have 2 options:

1. Use the ptr as a global variable.

2. Declare the ptr in main() and pass the address to fun() to alloacte inside fun() and free either in fun() or in main().



0
 
stefan73Commented:
Errm, correction: It's on the same man page as malloc, etc., but uses alloca.h
0
 
ankuratvbCommented:
Stefan,
Looks like its time for me to get a new compiler :~)
i hope gcc will support it,
0
 
stefan73Commented:
ankuratvb,
yes, it's even builtin:

#ifdef __GNUC__
#define alloca(size) __builtin_alloca(size)
#else
void * _EXFUN(alloca,(size_t));
#endif

Stefan
0
 
waysideConnect With a Mentor Commented:
Is it necessary to use new to allocate the memory?

If the buffer is small, and a fixed size, and doesn't need to live past the end of the function, just create it on the stack as an array:

ex:
int main()
{
 fun();
}

void fun()
{
  char str[100] = { \0' };
  int n;

  n = strlen(str);
  //some operations.
  return;
}
0
 
stefan73Commented:
wayside,
> create it on the stack as an array:
gcc also allows arrays of flexible size (probably using __builtin_alloca):

void arr_test(int asize){
    char buf[asize];
    ...
}

Stefan
0
 
waysideCommented:
> gcc also allows arrays of flexible size (probably using __builtin_alloca):

Nice. Microsoft's compiler doesn't allow this, although the runtime does have alloca().
0
 
stefan73Commented:
wayside,
Yes, there are lots of really nice extensions. Some of them went into ISO99 (such as variable length arguments for macros), others are still unique. Especially the extended ASM is great.

Here is a list:
http://gcc.gnu.org/onlinedocs/gcc-3.3.3/gcc/C-Extensions.html#C%20Extensions

Stefan
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.