Question

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

Asked by: expertintraining

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


This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2009-05-19 at 02:31:27ID24420220
Topic

C++ Programming Language

Participating Experts
6
Points
250
Comments
19

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Pointers
    Hi, I know that by using pointers execution speed or performance of application increases. I know that beacuse pointers holds the address of a variable so it can directly access that memory location.But first it has to search for that pointer variable which holds the ...
  2. Pointer to an int
    I have an array like this: int x[256] x is passed to a DLL as a pointer. The size is supposed to be 256 always, and every element of the array must contain a valid integer. What I need is a good way to check for those two conditions within the DLL. Note that I have no c...
  3. Pointers OR not?
    In many of the newer languages, they all claim they have removed the "pointers". Obviously I can see the advantage. But I wonder if it also casues some disadvantages? Let say I have a set of objects that uses a same set of data called "structures". Immagi...
  4. Pointers
    This is going to sound pretty stupid, but I am really having some conceptual problems with pointers. I'm a VB programmer and I've been learning C++ recreationally for the last few months, so please excuse my ignorance. Can someone explain to me in a nutshell why pointers ar...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: angelIIIPosted on 2009-05-19 at 02:32:33ID: 24419938

the first sets the array size to 10 items, the second just creates an empty array.

 

by: Let_Me_BePosted on 2009-05-19 at 02:48:49ID: 24420033

Second expression should not be syntactically valid according to ANSI C++.

 

by: mrjoltcolaPosted on 2009-05-19 at 06:29:16ID: 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

 

by: HooKooDooKuPosted on 2009-05-19 at 06:29:40ID: 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.

 

by: mrjoltcolaPosted on 2009-05-19 at 06:33:14ID: 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.

 

by: mrjoltcolaPosted on 2009-05-19 at 06:40:26ID: 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"

 

by: expertintrainingPosted on 2009-05-19 at 13:45:30ID: 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);

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:

Select allOpen in new window

 

by: Let_Me_BePosted on 2009-05-19 at 14:21:26ID: 24426773

Check 5.3.4 in ISO/IEC 14882:2003(E)

 

by: angelIIIPosted on 2009-05-19 at 14:23:52ID: 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.

 

by: mrjoltcolaPosted on 2009-05-19 at 14:38:53ID: 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.

 

by: evilrixPosted on 2009-05-19 at 15:29:23ID: 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).

 

by: evilrixPosted on 2009-05-19 at 15:30:42ID: 24427199

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

 

by: mrjoltcolaPosted on 2009-05-19 at 15:52:38ID: 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?

 

by: evilrixPosted on 2009-05-19 at 16:04:40ID: 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.

 

by: evilrixPosted on 2009-05-19 at 16:08:06ID: 24427425

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

 

by: Infinity08Posted on 2009-05-20 at 02:41:28ID: 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++.

 

by: evilrixPosted on 2009-05-20 at 02:45:10ID: 24429922

Thanks for joining the party I8 :)

 

by: Infinity08Posted on 2009-05-20 at 02:53:23ID: 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.

 

by: expertintrainingPosted on 2009-08-21 at 15:58:14ID: 31582911

Thanks all

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...