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;
}
You are allocating memory for p and q:
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:
Note that since you are making your pointers point to the other pointer’s allocated buffer, you might have to check which
deleteoperator corresponds to whichnewoperation.You should use
delete[]on the buffer allocated withnew[]anddeletewith the buffer allocated withnew.