Click here to Skip to main content
15,667,536 members
Articles / Programming Languages / C++
Posted 8 Apr 2009

Tagged as


4 bookmarked

New with Empty Bracket

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
8 Apr 2009CPOL1 min read
New with empty bracket

Have you ever written a statement like:

int *pnValue = new int[];

One of my friends asked me what will happen if the above statement is executed. Executed??? I though the code won't even compile. Surprisingly, it compiled and even returned a pointer. Wow, that was something unbelievable.

OK now the question is, what will be size of memory that pnValue points?

The two APIs in Windows that allocates and de allocates the memory are HeapAlloc and HeepFree. The CRT functions malloc and free are actually wrappers for the above API. The new, new[], delete, delete[] are again another wrapper around the malloc and free. So whenever you allocate some memory using new or new[], it will finally reach the HeapAlloc function. This function is defined as:

__in HANDLE hHeap,
__in DWORD dwFlags,
__in SIZE_T dwBytes

From the above definition, you can see that the third parameter to this function is the number of BYTES to be allocated. So to find out what "new int[]" returns, we can put a break point in the entry point of HeapAlloc and check the value of dwBytes (in dis assembly).

When I tried, the dwBytes turned out to be 1!!! This one byte cannot even hold one int variable. That means any further operation using such a pointer will possibly crash.

Another interesting thing is "int *pnValue = new int[0];" also returns a pointer pointing a memory of 1 byte long.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Written By
Software Developer (Senior)
Australia Australia
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

-- There are no messages in this forum --