开发者

delete a variable out of scope

int* func()
{
   int* i=new int[1];
   //do something
   return i; 
}

void fun开发者_开发技巧cc()
{
   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.


It should be delete [] tmp; because you're doing array new, but otherwise, it's correct.


As others have stated, you should use delete[] to delete arrays, not delete.

But, if you're asking whether it's okay to delete tmp because the memory it points to wasn't allocated with new, then your premise is incorrect.

It was allocated with new. The address of the memory that you allocate within the function for i is passed back to be stored in tmp, so it does point to memory that was allocated by new.

You're correct that i itself is out of scope at that point but memory allocated by new survives the scope change on exit from the function. And, since you're storing its location into tmp, you still have access to it.

Hence the deletion (once you make it an array deletion with []) is quite valid.


This is Undefined Behaviour™. You can only use delete if you used new. If you used new[], you MUST delete[] it. More than that, this is hideously unsafe code- you need a smart pointer.


No. new T[] should match delete []t. And new T should match delete t. Otherwise, your code would invoke undefined bevavior.

And it doesn't matter if you do delete []tmp outside the function. Its okay to do so. All that you need to keep in mind that the form of delete.


  • My spidey-senses tell me that you're wondering whether the dynamically-allocated int that you create in func is the same one that you attempt to delete in funcc.

    The answer is: yes. Although you don't use strictly the same pointer variable, both pointers point to the same object.

  • However, please remember to use delete[] (with the []) when you used new[] (with the []). Your code is broken until you fix this.


Also, try to avoid newing in one place and deleteing in another. Perhaps consider a std::vector instead, which is far less error-prone.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜