Hello everyone ,
As this is my first , I would like share something with you guys . I have been inspired by my friends who have been sharing their thoughts and other intersting stuffs via blogs since my university period. I thought of stating a techinal related blog soon after my graduation, unfortunely I couldn’t achive that so far . Today, that dream comes to an end and I have started to writing my first post here. Since , I like to share techical stuffs with you guys, I’ve grabed a topic call memory mangement in C++.
Coming days I will explain more advance and comprehensive memory management methods in C/C++, how low level memory allocation/deallocation works and performance optimiztion using memory management.
Memory allocation in C and C++ is somwhat different accoring to their standards and specifications. We will talk about that in detail later . First come to the point , We often make mistake in double pointer creation and deletion in C/C++. Fist we will look in to how C++ double pointer allocation and deallocation works .
Consider the following code:
Code:
int ia = 3;
int **ppA = new int*[ia];
for(int i=0; i < ia; ++i)
{
ppA[i] = new int[i+1];
}
delete [] ppA;
The above code snippet will generate memory leaks while we are running our program. Why? Because we are not freeing all the allocated memory. Because ppA is an array of pointers, with each of it's elements pointing to a separate memory block, so we have to free these block before freeing the array that holds the pointers.
We are actually allocating 4 + 8 + 12 = 24 bytes in three different memory blocks on the heap, plus the memory necessary to hold the pointers to those 24 bytes.
When you do this:
Code:
delete [] pAA;
we aree only freeing this memory holding the 3 pointers, not the memory they point to. So this will lead to a memory leak .
The above diagram dipicts that manipulation of internal memory . So in order to avoid the memory leaks we must free those blocks first:
Code:
for(i=0; i < ia; i++)
{
delete [] ppA[i];
}
delete [] pAA;
