Solved

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

Posted on 2004-04-05
18
230 Views
Last Modified: 2010-04-15
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.
0
Comment
Question by:netqueries
  • 7
  • 4
  • 2
  • +2
18 Comments
 
LVL 45

Accepted Solution

by:
sunnycoder earned 63 total points
ID: 10763344
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
 
LVL 4

Expert Comment

by:PerryDK
ID: 10763809
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
 
LVL 12

Expert Comment

by:stefan73
ID: 10763999
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
 
LVL 12

Expert Comment

by:stefan73
ID: 10764123
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
 
LVL 9

Expert Comment

by:ankuratvb
ID: 10764146
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
 
LVL 45

Expert Comment

by:sunnycoder
ID: 10764147
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
 
LVL 9

Expert Comment

by:ankuratvb
ID: 10764157
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
 
LVL 12

Expert Comment

by:stefan73
ID: 10764175
ankuratvb,
alloca is defined in stdlib.h on my Solaris here.

Stefan
0
What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

 
LVL 9

Expert Comment

by:ankuratvb
ID: 10764177
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
 
LVL 12

Expert Comment

by:stefan73
ID: 10764178
Errm, correction: It's on the same man page as malloc, etc., but uses alloca.h
0
 
LVL 9

Expert Comment

by:ankuratvb
ID: 10764186
Stefan,
Looks like its time for me to get a new compiler :~)
i hope gcc will support it,
0
 
LVL 12

Expert Comment

by:stefan73
ID: 10764300
ankuratvb,
yes, it's even builtin:

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

Stefan
0
 
LVL 14

Assisted Solution

by:wayside
wayside earned 62 total points
ID: 10764928
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
 
LVL 12

Expert Comment

by:stefan73
ID: 10765482
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
 
LVL 14

Expert Comment

by:wayside
ID: 10766114
> 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
 
LVL 12

Expert Comment

by:stefan73
ID: 10766215
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

Featured Post

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

Have you thought about creating an iPhone application (app), but didn't even know where to get started? Here's how: ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ Important pre-programming comments: I’ve never tri…
Preface I don't like visual development tools that are supposed to write a program for me. Even if it is Xcode and I can use Interface Builder. Yes, it is a perfect tool and has helped me a lot, mainly, in the beginning, when my programs were small…
The goal of this video is to provide viewers with basic examples to understand and use pointers in the C programming language.
The goal of this video is to provide viewers with basic examples to understand and use structures in the C programming language.

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now