1832005 Members
3231 Online
110034 Solutions
New Discussion

Memory management

 
SOLVED
Go to solution
Fedele Giuseppe
Frequent Advisor

Memory management

Hello,

I have the following doubt about variables memory management in C.

I have a function returning a pointer to "char":

char *func(){
....
char *x;
....
x = malloc(20);
....
return x;
}

and then I use it in the following way:

amb_buff = char[100];
...
for( ; ;)
{
...
sprintf(amb_buff, "%s", func());
...
}

My question is about the memory allocated for "x" var by "malloc" in the routine:

- is it freed after the "func" function return,
- or, at each iteration of the "for" cycle, a new 20 bytes of memory are added to the process memory amount?

In few words: does the total process memory increase undefinitely?

Thanks

Giuseppe Fedele


4 REPLIES 4
Venkatesh BL
Honored Contributor
Solution

Re: Memory management

Every malloc() call will allocate memory from process heap. You should call free() after you are done with the memory. You will see memory leak otherwise. You can confirm it with a tool like glance or ps.
James R. Ferguson
Acclaimed Contributor

Re: Memory management

Hi Giuseppe:

To add, as noted already, calling 'malloc()' [or its cousins] allocates memory to the 'heap' (a program's memory pool) while 'free()' returns that memory to the heap. This is designed for performance and is normal behavior. That is, the freed memory is given to the program's heap but _not_ to the operating system at large until the program finally terminates.

The heap can grow up to the size specified by 'maxdsiz' for 32-bit processes or up to 'maxdsiz_64bit' for 64-bit processes.

Regards!

...JRF...
Dennis Handly
Acclaimed Contributor

Re: Memory management

If you compile this with aCC6's +wlint +O2 you get:
procedure func: warning #20200-D: Potential null pointer dereference through x is detected (null definition:itrc_leak.c, line 5)
procedure main: warning #20201-D: Memory leak is detected
dirk dierickx
Honored Contributor

Re: Memory management

every malloc call should be freed when no longer needed. in this day and age, i don't use c anymore and moved on to some other languages (take a pick: python, java, etc.)

they are not as slow as you might think and help to maintain your sanity and program stability!!