Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting an array of pointers to functions?

Here is what I've copied from MSDN about new operator:

The new operator cannot be used to allocate a function, but it can be used to allocate pointers to functions. The following example allocates and then frees an array of seven pointers to functions that return integers.

int (**p) () = new (int (*[7]) ());
delete *p;

Well there is nothing strange with first line, it allocates an array of pointers to functions, but I just don't understand how the second deletes that array? I think it should be:

delete[] *p;

Can anyone explain this?

like image 809
codekiddy Avatar asked Nov 17 '11 06:11

codekiddy


2 Answers

Frankly speaking the right answer was written in the avakar's comment. The right code is

delete[] p;

delete *p; is incorrect for two reasons:

  1. we must use delete[] for all dynamically allocated arrays. Using delete will cause an undefined behaviour.
  2. pointers to static and member functions cannot be deleted
like image 176
Dmitry Sapelnikov Avatar answered Sep 24 '22 02:09

Dmitry Sapelnikov


If we add a typedef,

typedef int (*FPtr)();

the new statement can be rewritten as

FPtr *p = new FPtr[7];

so this is obvious that the resource should be released with

delete[] p;

as explained by others.


BTW, the MSDN page for VS 2008 and above does use the correct code.

int (**p) () = new (int (*[7]) ());
delete [] p;
like image 33
kennytm Avatar answered Sep 23 '22 02:09

kennytm