What is the difference between int *pointer = new int[100]; and int *pointer = new int[];

Posted on 2009-05-19
Last Modified: 2012-05-07
What is the difference between int *pointer = new int[10]; and int *pointer = new int[];
Are their any gotchas associated with the second form?

Question by:expertintraining
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 5
  • 2
  • +4
LVL 143

Expert Comment

by:Guy Hengel [angelIII / a3]
ID: 24419938
the first sets the array size to 10 items, the second just creates an empty array.
LVL 12

Expert Comment

ID: 24420033
Second expression should not be syntactically valid according to ANSI C++.
LVL 40

Expert Comment

ID: 24421723
>>int *pointer = new int[];

That is not C++ (as Let_Me_Be pointed out). Did you try compiling it?

C++ requires array dimensions to be provided during allocation / creation, or that the compiler can determine the array size (ie. a constant expression).

The only places you could put empty brackets in C++ (that I can think of) would:
1) As a function argument.

void foo(int arr[]) {   // same as int * arr


2) In constant initialization

int pointer[] = { 1, 2, 3 };   // legal, compiler can tell array is of size 3

// These are illegal
int pointer2[] = new int[10];  // not legal because "new" is not a constant expression
int pointer2[10] = new int[];  // not legal, cannot create empty array
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

LVL 16

Expert Comment

ID: 24421727
Since int[] is pretty much the same thing as int* (for an array variable is really just a pointer to the 1st element of an array) your question could be morphed into "What is the difference between...
int* p = new int[10];
int*p = new int*;

Both create a pointer to an integer.  But the 1st syntax also allocates memory for 10 integer values.  The second syntax only allocates space for the pointer.  It doesn't allocate any memory space for data.
LVL 40

Expert Comment

ID: 24421764
>>int*p = new int*;

I disagree.

new returns a pointer, by definition, so new int * returns a pointer to a pointer, so your example is not correct.
LVL 40

Expert Comment

ID: 24421853
@HooKooDooKu writes:
>> The second syntax only allocates space for the pointer.  It doesn't allocate any memory space for data.

Besides being incorrect syntax (illegal) in C++, that statement is incorrect. You cannot use new in C++ without allocating memory. The fact that int * p allocates space for the pointer is due to the declaration of int * p in the local scope, not due to using "new"

Author Comment

ID: 24426486
First of all thanks your all you reply's,
Yes I need to look up the standard, but so far this is what I found with Visual Studio 2008:

1. All code compiles and links
2. When code where only int *pArray = new int[10]; is used we have no problems
3. When code int *pArrayWrong = new int[]; is added, we get right output but I get the following heap corruption detected and exception msgs.
Heap corruption detected at 00345E10
First-chance exception at 0x7c911689 in PrimitiveArray.exe: 0xC0000005: Access violation reading location 0x0000752f.
Heap corruption detected at 00343B48
I would have thought that if the second call is not c++ standard compliant that the we would get a compiler error, but no such I guess its one of those gotchas in VS 2008.

Also, mrjoltcola and Let_Me_Be or anyone else can you point me to the standard (section #) where it states that the second call is invalid.

	int *pArray = new int[10];
	pArray[0] = 111;
	pArray[1] = 222;
	pArray[2] = 333;
	pArray[3] = 444;
	pArray[4] = 555;
	pArray[5] = 666;
	pArray[6] = 777;
	pArray[7] = 888;
	pArray[8] = 999;
	pArray[9] = 2999;
	printMyArray(pArray, arraySize);
	int *pArrayWrong = new int[];
	pArrayWrong[0] = 1111;
	pArrayWrong[1] = 2222;
	pArrayWrong[2] = 3333;
	pArrayWrong[3] = 4444;
	pArrayWrong[4] = 5555;
	pArrayWrong[5] = 6666;
	pArrayWrong[6] = 7777;
	pArrayWrong[7] = 8888;
	pArrayWrong[8] = 9999;
	pArrayWrong[9] = 29999;
	printMyArray(pArrayWrong, arraySize);
//void printMyArray(int *ptr, int &arraySize);

Open in new window

LVL 12

Expert Comment

ID: 24426773
Check 5.3.4 in ISO/IEC 14882:2003(E)
LVL 143

Expert Comment

by:Guy Hengel [angelIII / a3]
ID: 24426796
the problem with the second code is that you define, as I said, an empty array.
so, an attempt to
 pArrayWrong[0] = 1111;
in that case makes C++ trying to assign a variable to a pointer where nothing has been allocated.
LVL 40

Expert Comment

ID: 24426904
Whether visual C++ allows it or not, trying this:

int size = sizeof(int []);

results in a compile error. So its clear that the Microsoft compiler doesn't REALLY think it is a type

int size = sizeof(int [1]);

results in size == 4 (or 8 on 64-bit)

However, further investigation by tracing this:

      int * p = new int[];
      int * p2 = new int[];

Shows that Visual C++ is treating "new int[]" like "new int" or "new int[1]" and allocating a single int, because the pointers are consecutive 32-bit addresses.

Now as far as your sample above, it doesn't prove anything regarding the allocated size. I can remove the whole "new int[]" and just say:

int * pArray;
pArray[1434324] = 1;

Which is just as wrong. The question is, what does Microsoft Visual C++ think "new int[]" means, because it is obviously returning a memory address from the allocator of 1 * sizeof(int), so it is not a zero length array.
LVL 40

Expert Comment

ID: 24427189
The C++ standard says this about new [] Array forms                                                                  []
       void* operator new[](std::size_t size) throw(std::bad_alloc);
  Effects: The allocation function ( called by the array form of a new-expression (5.3.4) to allocate
     size bytes of storage suitably aligned to represent any array object of that size or smaller.211)
  Replaceable: a C++ program can define a function with this function signature that displaces the default
     version defined by the C++ Standard library.
  Required behavior: Same as for operator new(std::size_t). This requirement is binding on a
     replacement version of this function.

However is also states this... Replacement functions                                                            [lib.replacement.functions]
  Clauses 18 through 27 describe the behavior of numerous functions defined by the C++ Standard Library.
  Under some circumstances, however, certain of these function descriptions also apply to replacement func-
  tions defined in the program (17.1).
  A C++ program may provide the definition for any of eight dynamic memory allocation function signatures
  declared in header <new> (3.7.3, clause 18):
   operator new(size_t)
   operator new(size_t, const std::nothrow_t&)
   operator new[](size_t)
   operator new[](size_t, const std::nothrow_t&)
   operator delete(void*)
   operator delete(void*, const std::nothrow_t&)
   operator delete[](void*)
   operator delete[](void*, const std::nothrow_t&)
  The programs definitions are used instead of the default versions supplied by the implementation (18.4).
  Such replacement occurs prior to program startup (3.2, 3.6).

This implies that the standard new[] as defined in the standard can be overridden, legitimately. It seems this is what happens in Visual Studio, It seems Microsoft have provided a version of new[] that defines size with a default value to perform a 0 sized head allocation (I don't have access to Windows or Visual Studio at the moment to conform this postulation), in much the same way as you can legitimately do malloc(0). The idea behind this odd syntax (if I recall correctly) was to prevent programmers having to write extra code to check for the possibility of allocating 0 bytes during a heap allocation. malloc(0) and a subsequent free are perfectly valid, the same is true of new[0] (although gcc does warn).
LVL 40

Expert Comment

ID: 24427199
^^^ I hate how wordy and hard to decipher the C++ standard is sometimes :)
LVL 40

Expert Comment

ID: 24427338
evilrix, I like your theory, I am just curious what a no-arg new[] means, in regards to the overloaded signatures above. Is there a default parmeter for the size_t signature?
LVL 40

Expert Comment

ID: 24427407
>> I am just curious what a no-arg new[] means, in regards to the overloaded signatures above. Is there a default parmeter for the size_t signature?
I tried playing with this earlier at work (the only place I have access to VS since I am 100% Linux at home) and the behavior I witnessed (looking at a memory dump) when doing the following....

int * p = int[](); // Adding () forces it to call default constructor for int, thus zeroing out memory

Was the same as this....

int * p = int[0]();

However, I didn't get time to investigate further due to work pressures including looking at how new[] was defined. I can only guess that microsoft define it to have a default param, something like...

void * operator new[](size_t s = 0)

Like I said though, this is purely a postulation.
LVL 40

Expert Comment

ID: 24427425
I've called for reinforcements in trying to get a definitive answer for this :)
LVL 53

Accepted Solution

Infinity08 earned 250 total points
ID: 24429902
From MSDN ( :

        "When allocating an array using the new operator, the first dimension can be zero  the
        new operator returns a unique pointer."

And also ( :

        "If the request is for zero bytes of storage, operator new returns a pointer to a distinct
        object (that is, repeated calls to operator new return different pointers)."

That is conforming to the C++ standard that allows allocating 0 bytes of dynamic memory, and requires the new[] operator to return a unique non-NULL pointer value in that case. However, dereferencing that pointer results in undefined behavior.

        [5.3.4] "When the value of the expression in a direct-new-declarator is zero, the
        allocation function is called to allocate an array with no elements."

so, that part (passing 0 as a dimension for the new[] operator) of Visual C++'s behavior is correct.

However, passing NO dimension to the new[] operator is not standard compliant. The C++ grammar does not allow that :

            [ expression ]
            direct-new-declarator [ constant-expression ]

So, what Visual C++ does is an extension to the C++ standard

Now, how does it do that ? It can't do it using a default argument, as the standard forbids that :

        "... The first parameter shall have type size_t (18.1). The first parameter shall not have an associated default argument (8.3.6). ..."

It wouldn't really make sense to do it that way either, since this is basically a responsibility of the parser which "translates" the line of code to a call to the appropriate new operator (or new[] operator). It seems that the Visual C++ parser assumes 0 if the dimension is absent.

So, to answer the question :

new int[] is invalid in C++.
Visual C++ interpretes it as new int[0] (as an extension to the C++ standard), which is valid C++.
LVL 40

Expert Comment

ID: 24429922
Thanks for joining the party I8 :)
LVL 53

Expert Comment

ID: 24429962
No problem ;) I hope I've been able to shed some light on the issue ... Or at least that I've not added any more confusion heh.

Author Closing Comment

ID: 31582911
Thanks all

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Unlike C#, C++ doesn't have native support for sealing classes (so they cannot be sub-classed). At the cost of a virtual base class pointer it is possible to implement a pseudo sealing mechanism The trick is to virtually inherit from a base class…
Often, when implementing a feature, you won't know how certain events should be handled at the point where they occur and you'd rather defer to the user of your function or class. For example, a XML parser will extract a tag from the source code, wh…
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.

756 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question