Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ comparing a pointer to NULL

I'm fairly new to C++ so bear with me.

I have the following program to learn about dynamic memory allocation.

#include<iostream>
#include<new>

using namespace std;

int main ()
{
        int i,n;
        int * p;
        cout << "How many numbers would you like to enter? ";
        cin >> i;

        p = new (nothrow) int [i];

        if (NULL == p){
                cout << "Not enough memory!";
        }else{
                for (n=0; n<i; n++){
                        cout << "Enter a number: ";
                        cin >> p[n];
                }
                cout << "You have entered:  ";
                for(n=0; n<i; n++){
                        cout << p[n] << ", ";
                }
                delete[] p;
        }
        return 0;
}

So long as a sensible amount is entered initially the program runs as expected. But when a huge number (1000000000000) is entered I expected the output "Not enough memory" when in fact it starts printing "Enter a Number: " presumably 1000000000000 times, obviously I haven't waited for output. Since this is in the "else" part of the check, why is this happening? I guessed that the comparison isn't working. Any help is appreciated. Thanks.

like image 946
Matt Pellegrini Avatar asked Jun 01 '26 07:06

Matt Pellegrini


1 Answers

If the first number you enter is more 2^31 one of the possible reasons is the following:

After you give invalid data the first time cin becomes in invalid state and each next data input operation (e.g. >> ) does nothing (so it doesn't wait for your input) unless your explicitly return cin to normal state.

One of the possible solutions for you are: add after

cin >> p[n];

this piece of code:

if (cin.fail()) {
   cout << "Bad data" << endl;
   cin.clear();
}
like image 122
sasha.sochka Avatar answered Jun 04 '26 00:06

sasha.sochka



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!