Results 1 to 6 of 6
Hi guys,
I am in a problem to manage memory in c++. I just can't figure out where in my program memory leaks. I used "new" and "delete" very carefully.
...
- 11-22-2011 #1Just Joined!
- Join Date
- Nov 2011
- Posts
- 4
Help with memory management in C++
Hi guys,
I am in a problem to manage memory in c++. I just can't figure out where in my program memory leaks. I used "new" and "delete" very carefully.
1. Can anyone help me with a tool in linux to detect memory leaks?
2. Can anyone please share possible scenarios where "memory leak" may occur?
Following are my possible strategies that I applied to avoid memory leak:
1. After declaration of a pointer, I assign 0 to it.
Box * b =0;
2. Before using "new", I check whether the pointer is 0 or not.
if(!b)3. I free the memory at appropriate places:
b = new Box();
Class Segment
{
private:};
Box * b;
Box ** arrBox;
Segment::Segment()
{
b = new Box();}
arrBox = new Box*[10];
for (int i =0; i < 10; i++)
arrBox[i] = new Box();
~Segment::Segment()
{
if(b)}
{
delete b;}
b = 0;
for (int i = 0; i < 10; i++)
{
if(arrBox[i])}
{
delete arrBox[i];}
arrBox[i] = 0;
if(arrBox)
{
delete [] arrBox;}
arrBox = 0;
4. I have also avoided the case where I am initializing an object in a loop:
while(i<10)
{
b =new Box();}
i++;
The above are the cases that I checked for memory management. Please share your ideas to have more situations where memory leak may occur.
Thanks,
SaikatLast edited by saikat056; 11-22-2011 at 06:23 PM.
- 11-22-2011 #2Linux Guru
- Join Date
- May 2011
- Posts
- 1,843
I haven't looked at your code, but I can suggest Valgrind to you. It may already be available in your distro's repos.
- 11-22-2011 #3Linux Newbie
- Join Date
- Mar 2010
- Posts
- 121
I'd also recommend valgrind. Also consider using smart pointers like auto_ptr to make life easier for yourself.
- 11-22-2011 #4
I believe that what you are doing here:
is creating an array of 10 Box instances, then looping around and overwriting each instance in the array with a new instance created with new. This will leak memory. Perhaps instead of using an array like this, you should consider using the STL, something like std::vector or std::array should do it.Code:Segment::Segment() { b = new Box(); arrBox = new Box[10]; for (int i =0; i < 10; i++) arrBox[i] = new Box();Linux user #126863 - see http://linuxcounter.net/
- 11-22-2011 #5Just Joined!
- Join Date
- Nov 2011
- Posts
- 4
The line
arrBox = new Box[10];
should be
arrBox = new Box*[10];
Thank you for help!
- 11-22-2011 #6Just Joined!
- Join Date
- Nov 2011
- Posts
- 4
Valgrind is very helpful. Thank you!!


Reply With Quote