Will delete[] with void* cause memory leak? [duplicate]
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.
精彩评论