You are here:

C/what happens if I do this...

Advertisement


Question
what happens if I do this (in C on unix)..

 /* program starts */
int *p;
p = (int *) calloc(100, sizeof(int));
 /* other lines of code where use 'p' */  
p = (int *) calloc(10, sizeof(int));
 /* in above line use calloc, instead of realloc */
 /* lines of code, and use 'p' */
free(p);
 /*program ends */

Want to know...?
1)how much memory will it free?
2)will there be any memory leak? If yes then how to check it?

Answer
Here you are allocating (100 * sizeof (int)) to p.
Again in the next line, you are overwriting it by allocating another (10 * sizeof(int)).
So, because of this, you have lost the address that you have got with the first allocation.

Becasue of this, if you try to free(p), it will free only the 10 locations that was allocated in the end.

Obviously there is a memory leak.
And there are some memory profilers available, which will very easily catch these type of leaks.
You can try memprof which is available for unix platforms.

Also, you can search in the google for any other better profilers.

Hope this helps.

C

All Answers


Answers by Expert:


Ask Experts

Volunteer


Narendra

Expertise

I can answer questions in C related to programming, data structures, pointers and file manipulation. I use Solaris for doing C code and if you have questions related to C programming on Solaris, I will be able to help better.

Experience

6.5

Organizations belong to
Sun Microsystems

Awards and Honors
Brain Bench Certified Expert C programmer.
Advanced System Software Certified

©2012 About.com, a part of The New York Times Company. All rights reserved.