My pointer p is inside a function, will i get memory leak with this code.
for(k=0;k< 3;k++)
{
int *p=NULL;
int val = bBreak[k+1] - bBreak[k];
p = new int [val+1];
p = &buff[bBreak[k]];
for(int i=0;i< val;i++)
{
cout<<"\n"<<p[i]<<endl;
}
}
Yes! You never free the memory. You should call delete/delete[]
for every piece of memory you allocate with new/new[]
.
Yes, you will
p = new int [val+1]; //allocate array on the heap
p = &buff[bBreak[k]]; //new allocated array is leaked because you lost the pointer to it
//and you are not able to call 'delete[]' to free the memory
Generally, every call to operator new
should be paired with call of operator delete
or delete[]
Yes. You must delete
every memory you allocate with new
.
p = new int [val+1];
p = &buff[bBreak[k]]; // here you lose track of the memory you've just allocated
If you don't want to do memory management by-hand, use a std::vector<int>
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.