[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: How to test memory allocation with new ?
From: |
Method Man |
Subject: |
Re: How to test memory allocation with new ? |
Date: |
Tue, 2 Nov 2004 03:50:48 -0500 |
"Sharad Kala" <no_spam.sharadk_ind@yahoo.com> wrote in message
2umrtrF2cn54gU1@uni-berlin.de">news:2umrtrF2cn54gU1@uni-berlin.de...
>
> "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.
>
Do you mean both statements are problematic? Shouldn't 'pp[0] = 0' be OK
since it is equivalent to *pp = 0 (assigning the allocated char the null
value)?
Re: How to test memory allocation with new ?, Cosmin Calinescu, 2004/11/01
Re: How to test memory allocation with new ?, Larry I Smith, 2004/11/01