[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
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