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

What is the difference between int *pointer = new int[10]; and int *pointer = new int[];
Are their any gotchas associated with the second form?


expertintrainingAsked:
Who is Participating?
 
Infinity08Connect With a Mentor Commented:
From MSDN (http://msdn.microsoft.com/en-us/library/kewsb8ba(VS.80).aspx) :

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

And also (http://msdn.microsoft.com/en-us/library/t48aek43(VS.80).aspx) :

        "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 :

        direct-new-declarator:
            [ 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 :

        [3.7.3.1]
        "... 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++.
0
 
Guy Hengel [angelIII / a3]Billing EngineerCommented:
the first sets the array size to 10 items, the second just creates an empty array.
0
 
Let_Me_BeCommented:
Second expression should not be syntactically valid according to ANSI C++.
0
Cloud Class® Course: C++ 11 Fundamentals

This course will introduce you to C++ 11 and teach you about syntax fundamentals.

 
mrjoltcolaCommented:
>>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
0
 
HooKooDooKuCommented:
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];
...and...
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.
0
 
mrjoltcolaCommented:
>>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.
0
 
mrjoltcolaCommented:
@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"
0
 
expertintrainingAuthor Commented:
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 luck...so 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

0
 
Let_Me_BeCommented:
Check 5.3.4 in ISO/IEC 14882:2003(E)
0
 
Guy Hengel [angelIII / a3]Billing EngineerCommented:
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.
0
 
mrjoltcolaCommented:
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.
0
 
evilrixSenior Software Engineer (Avast)Commented:
The C++ standard says this about new []

  18.4.1.2 Array forms                                                                  [lib.new.delete.array]
       void* operator new[](std::size_t size) throw(std::bad_alloc);
  Effects: The allocation function (3.7.3.1) called by the array form of a new-expression (5.3.4) to allocate
1
     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
2
     version defined by the C++ Standard library.
  Required behavior: Same as for operator new(std::size_t). This requirement is binding on a
3
     replacement version of this function.

However is also states this...

  17.4.3.4 Replacement functions                                                            [lib.replacement.functions]
  Clauses 18 through 27 describe the behavior of numerous functions defined by the C++ Standard Library.
1
  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
2
  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).
3
  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).
0
 
evilrixSenior Software Engineer (Avast)Commented:
^^^ I hate how wordy and hard to decipher the C++ standard is sometimes :)
0
 
mrjoltcolaCommented:
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?
0
 
evilrixSenior Software Engineer (Avast)Commented:
>> 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.
0
 
evilrixSenior Software Engineer (Avast)Commented:
I've called for reinforcements in trying to get a definitive answer for this :)
0
 
evilrixSenior Software Engineer (Avast)Commented:
Thanks for joining the party I8 :)
0
 
Infinity08Commented:
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.
0
 
expertintrainingAuthor Commented:
Thanks all
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.