[2 days left] What’s wrong with your cloud strategy? Learn why multicloud solutions matter with Nimble Storage.Register Now

x
?
Solved

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

Posted on 2009-05-19
19
Medium Priority
?
937 Views
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?


0
Comment
Question by:expertintraining
[X]
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
19 Comments
 
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.
0
 
LVL 12

Expert Comment

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

Expert Comment

by:mrjoltcola
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
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
LVL 16

Expert Comment

by:HooKooDooKu
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];
...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
 
LVL 40

Expert Comment

by:mrjoltcola
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.
0
 
LVL 40

Expert Comment

by:mrjoltcola
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"
0
 

Author Comment

by:expertintraining
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 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
 
LVL 12

Expert Comment

by:Let_Me_Be
ID: 24426773
Check 5.3.4 in ISO/IEC 14882:2003(E)
0
 
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.
0
 
LVL 40

Expert Comment

by:mrjoltcola
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.
0
 
LVL 40

Expert Comment

by:evilrix
ID: 24427189
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
 
LVL 40

Expert Comment

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

Expert Comment

by:mrjoltcola
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?
0
 
LVL 40

Expert Comment

by:evilrix
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.
0
 
LVL 40

Expert Comment

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

Accepted Solution

by:
Infinity08 earned 1000 total points
ID: 24429902
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
 
LVL 40

Expert Comment

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

Expert Comment

by:Infinity08
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.
0
 

Author Closing Comment

by:expertintraining
ID: 31582911
Thanks all
0

Featured Post

Technology Partners: 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!

Question has a verified solution.

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

When writing generic code, using template meta-programming techniques, it is sometimes useful to know if a type is convertible to another type. A good example of when this might be is if you are writing diagnostic instrumentation for code to generat…
Written by John Humphreys C++ Threading and the POSIX Library This article will cover the basic information that you need to know in order to make use of the POSIX threading library available for C and C++ on UNIX and most Linux systems.   [s…
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.

649 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