Reputation: 119
Is there anything wrong with the following program? Do I have to delete the pointers so I don't have a memory leaks?
Please help.
#include<iostream>
using namespace std;
int main()
{
int x=2, y=3;
int *p,*q;
int **pp;
cout<<x<<","<<y<<endl;//x=2,y=3
p=&x;
q=&y;
cout<<*p<<","<<*q<<endl;//*p=2,*q=3
p=new int [5];
p[2]=9;
q=p+x;
p[0]=8;
cout<<*p<<","<<*q<<endl;//*p=8,*q=9
pp=&p;
cout<<pp[0][2]<<endl;//pp[0][2]=9
q=new int;
p=q;
*p=5;
*q=7;
cout<<*p<<","<<*q<<endl;//*p=7,*q=7
delete p;
p=NULL;
}
Upvotes: 0
Views: 6053
Reputation: 21910
You are allocating memory for p and q:
p=new int [5];
/* ... */
q=new int;
But you are only freeing p using an invalid operator, since arrays should be deleted using delete[]. You should at some point free both p and q using:
delete[] p;
delete q;
Note that since you are making your pointers point to the other pointer's allocated buffer, you might have to check which delete
operator corresponds to which new
operation.
You should use delete[]
on the buffer allocated with new[]
and delete
with the buffer allocated with new
.
Upvotes: 3
Reputation: 206646
You do have a memory leak.
Simplest rule to do this is:
Count the number of new
& new []
in your program and you should have exactly same number of delete
and delete []
respectively.
Your program has a new []
and a new
but only a single delete
so you are leaking the memory allocated through new []
.
Makeshift Solution:
You should be calling delete []
on exactly the same address returned by new []
Most appropriate Solution:
You should never manually manage dynamic memory You should be using RAII and Smart pointers to do this for you, it is the ideal and the most appropriate C++ way to do this.
Upvotes: 3