0

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 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*
Community
  • 1
  • 1
RichardLiu
  • 1,902
  • 1
  • 19
  • 18
  • It will not compile in most of the compilers as it would not be possible for delete to know how much memory needs to be freed for a void pointer. – Arunmu Apr 27 '11 at 03:58

2 Answers2

1

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.

Marcelo Cantos
  • 181,030
  • 38
  • 327
  • 365
  • 5
    It may compile but the results are definitely undefined. – James McNellis Apr 27 '11 at 03:33
  • 2
    Generally true, but the quirk here (deemphasised by the lack of mention in the text of the question): he's deleting a `void` pointer! – Tony Delroy Apr 27 '11 at 03:36
  • Yes..but it seems that g++ may let it pass, with only a warning message "warning: deleting 'void*' is undefined". Guess I should modify my question to make it more clarify. – RichardLiu Apr 27 '11 at 04:17
1

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.