help-gplusplus
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: How to test memory allocation with new ?


From: David Lindauer
Subject: Re: How to test memory allocation with new ?
Date: Mon, 01 Nov 2004 22:59:43 GMT

what is the syntax for specifying nothrow?

Thanks,

David

Sharad Kala wrote:

> "jjleto" <jjleto@laposte.net> wrote in message
> > Hello,
> >
> > How do I handle the following :
> >
> > ------>
> > #include <iostream>
> > using namespace std;
> >
> > int main()
> > {
> > int n = 0x7FFFFFFF;
> > char *pp = new char(n);
>
> This does not do what you are thinking. It allocates memory for one char and
> tries to initialize it with 0x7FFFFFFF. To allocate an array use -
> char *pp = new char[...];
>
> > if ( pp != NULL ) {
>
> This is  a big misconception that new returns NULL on failure. The fact is
> that it throws std::bad_alloc exception on failure (unless you specify
> nothrow)
>
> > pp[0] = 0;
> > pp[n-1] = 0;
>
> This is the cause of your segmentation fault. You are trying to write to an
> illegal memory location.
>
> > cout << "OK" << endl;
> > } else {
> > cout << "FAILED" << endl;
> > }
> > }
>
> Sharad


reply via email to

[Prev in Thread] Current Thread [Next in Thread]