int* func()
{
int* i=new int[1];
//do something
return i;
}
void funcc()
{
int* tmp=func();
//delete allocated memory after use
delete tmp;
}
should delete working as described in the second function be a correct use ?
I think I didn’t allocate memory to it by new ? new was used in the first, to be sure.
As others have stated, you should use
delete[]to delete arrays, notdelete.But, if you’re asking whether it’s okay to delete
tmpbecause the memory it points to wasn’t allocated withnew, then your premise is incorrect.It was allocated with
new. The address of the memory that you allocate within the function foriis passed back to be stored intmp, so it does point to memory that was allocated bynew.You’re correct that
iitself is out of scope at that point but memory allocated bynewsurvives the scope change on exit from the function. And, since you’re storing its location intotmp, you still have access to it.Hence the deletion (once you make it an array deletion with
[]) is quite valid.