开发者

Will delete[] with void* cause memory leak? [duplicate]

开发者 https://www.devze.com 2023-03-01 02:50 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: Is it safe to delete a void pointer?
This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Is it safe to delete a void pointer?

Will the following code cause memory leak?

void *ptr = new long [10];
delete[] ptr; // note: ptr is 开发者_StackOverflow中文版a void*

[EDIT] The code above will generate a warning message during compiling to specify it "undefined". I ask this cause I'm wondering how does C++ handle memory ranges when delete[] is called. I should change my question to make it more specified.

Will the following code cause memory leak?

char *ptr = (char *)(new long [10]);
delete[] ptr; // note: ptr is a char*


No. Leaving delete[] out will cause a leak. BTW, it should be long* ptr. I don't think the delete[] will even compile with a void* argument.


I tried the following program (slight modification of this example):

#include <iostream>
#include <new>
using namespace std;

struct myclass {
  myclass() {cout <<"myclass constructed\n";}
  ~myclass() {cout <<"myclass destroyed\n";}
};

int main () {
  void * pt = new myclass[3];
  delete[] pt;

  return 0;
}

using g++ and got the following compilation warning:

leaky.cpp: In function ‘int main()’:
leaky.cpp:13: warning: deleting ‘void*’ is undefined

And when you run it...fail! The process dies (invalid pointer) when you attempt to delete that pointer.

0

精彩评论

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

关注公众号