Is there a way to distinguish between the new and the new [] return value?

Consider this code:

int *p = new int;
cout << sizeof(*p);
delete p;

As expected, the result is 4. Now consider this other code:

int *p = new int[10];
cout << sizeof(*p);
delete[] p;

I expected to get 40 (the size of the allocated array), however the result is still 4 .

Now suppose I have a function int *foo()that returns a pointer to a structure created using newor using new[](but I don't know which one):

int *p = foo();

My question is: is there a way (or hack) to know if pa single integer or an array of integers points to ?

Please keep in mind that this is just a theoretical question. I will not write real code this way.

+3
source share
7

, . , , , new new[].

, :

 cout << sizeof(*p);

4 , p int, * p , (.. int), int 4. , new[] , sizeof .

+4

, - ( 4 sizeof() ). , , .

+3

p : int *. sizeof , . .

. , , <int> . (, vector <int> :: size()) .

+2

sizeof (x) , x, .

.

sizeof (* foo), foo - bar *, , sizeof(bar)

+2

, .

: ?

" , delete [] delete", , - , .

+1

, , . 1:

return new int[1];
+1

-, sizeof(*p) , 4.

, , p int int[]?

There is a standard way . However, you can hack into the platform and recognize it. For example, if you try to print p[-1], p[-2], ..., p[-4] etc.for specific compilers (say linux in my case), you will see a specific pattern in the value of these locations. However, this is just a hack, and you cannot always rely on it.

0
source

All Articles