new not throwing bad_alloc

J

Jacek Dziedzic

Hi!

I accidentally did something like

float *ptr = new float[n*9];

where n was accidentally left uninitialized (and equal to something
like -1073372080) and my program coredumped.

I always thought that new was supposed to throw bad_alloc
when something goes bad with memory allocation... but
perhaps that isn't the case when a negative value is passed
within the [ ]?

BTW, what is the *type* of what is placed in between the [ ]
in new? int? unsigned int? size_t?

- J.
 
J

Jacek Dziedzic

Victor Bazarov said:
[...]
The value is promoted to std::size_t, which is defined in
<cstddef>, and can be unsigned, for all we know.
So, passing a negative value could have the same effect as
passing a large positive one.

I see.
Some older, non-compliant, compilers sometimes return null
pointer instead of throwing std::bad_alloc. Check with the
compiler docs.

Oh my... and I've just flamed my colleague for making
sure the pointer was not null after every new operation :],
telling him to either wrap the new in try/catch or don't
care and have an exception thrown.
I know it's out of scope of the NG, but I'm using gcc-3,
so I suppose it should be compliant.
std::size_t. Of course, whatever you place there should be
either converted or promoted to std::size_t.

I forgot to say I had an int there.

Still... the program crashed *even before* I tried to
dereference or otherwise use the (potentially) null pointer.
It never came back from the new line, so no pointer was
in fact returned! Could it be that the crash was a way of
manifesting an unhandled exception?

- J,
 
V

Victor Bazarov

Jacek Dziedzic said:
[...] the program crashed *even before* I tried to
dereference or otherwise use the (potentially) null pointer.
It never came back from the new line, so no pointer was
in fact returned! Could it be that the crash was a way of
manifesting an unhandled exception?

Yes, it very well could. Unhandled exceptions cause 'terminate'
function to be called.

Victor
 
K

Kevin Goodsell

Victor said:
The value is promoted to std::size_t, which is defined in <cstddef>,
and can be unsigned, for all we know. So, passing a negative value
could have the same effect as passing a large positive one.

size_t, in fact, must be unsigned unless I am mistaken.

-Kevin
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,564
Members
45,039
Latest member
CasimiraVa

Latest Threads

Top