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: Sharad Kala
Subject: Re: How to test memory allocation with new ?
Date: Mon, 1 Nov 2004 18:57:52 +0530

"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]