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: Larry I Smith
Subject: Re: How to test memory allocation with new ?
Date: Mon, 01 Nov 2004 16:36:10 GMT
User-agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.7.2) Gecko/20040906

jjleto wrote:
Hello,

How do I handle the following :

------>
    #include <iostream>
    using namespace std;

    int main()
    {
        int n = 0x7FFFFFFF;
        char *pp = new char(n);
        if ( pp != NULL ) {
            pp[0] = 0;
            pp[n-1] = 0;
            cout << "OK" << endl;
        } else {
            cout << "FAILED" << endl;
        }
    }
------>


It compiles OK, but when I run it, I get a segmentation fault. I thought that testing a NULL value was enough for testing memory allocation (or perhaps it is a bug ? I use gcc (GCC) 3.3.4)

Regards,
jjleto

#include <iostream>
using namespace std;

int main()
{
    char * pp;

    // given this value, 'new' will fail if less than 2GB of free RAM
    // is available
    int n = 0x7FFFFFFF;

    try
    {
        cout << "Allocate an array of " << n << " bytes in RAM" << endl;
        pp = new char[n];
    }
    catch (bad_alloc)
    {
        cout << "Allocation Attempt Failed" << endl;
        return 1;
    }

    pp[0] = 0;
    pp[n - 1] = 0;
    cout << "OK" << endl;

    delete[] pp;  // free the allocated array

    return 0;
}

Regards,
Larry

--
Anti-spam address, change each 'X' to '.' to reply directly.


reply via email to

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