I am writing a simple C++ Program which allocates dynamic memory to my Program and then deletes this memory. Here is my Program:
#include <iostream>
#include <new>
using namespace std;
int main ()
{
int i,n;
int * p;
cout << "How many numbers would you like to type? ";
cin >> i;
p= new (nothrow) int[i];
if (p == nullptr)
cout << "Error: memory could not be allocated";
else
{
for (n=0; n<i; n++)
{
cout << "Enter number: ";
cin >> p[n];
}
cout << "You have entered: ";
for (n=0; n<i; n++)
cout << p[n] << ", ";
delete[] p;
}
return 0;
}
In the above program when I input the value of i (Number of inputs) equal to or less than 2 Billion than this program works as expected. However when I enter anything above 2 Billion like 3 Billion or higher, this program goes in an infinite loop without taking a number input in my for loop.
I am expecting this program to fail when I enter a very high value for i by saying it could not allocate the memory.
As per my understanding, I think when I enter a very high value of int i, I am going out of bound for integer data type but still in this case, it should take number input from me in for loop as I have a cin statement there instead of going in for loop or memory allocation should fail simply.
When I changed type of i from int to long then it works but I am curious to know for i of type int, why it goes in infinite loop instead of taking values when it sees cin in for loop?
I am running this program on Mac OS X and compiling it using g++ compiler.
1) You are trying assign to
int
value bigger than 2147483647, which is usually maximum value for this type. Generally, if you want to handle such a large numbers, you should uselong long int
(or something from<cstdint>
for better portability).2) You don't clear state of
cin
after it fails. The code bollow generate infinite loop:You can solve it this way:
3) You are trying to create a really big array. You need a few GiB of contiguous memory to this. Even if you succeed allocate the array, it is still a design issue. You should use many of smaller arrays or use/create a suitable container.
The maximum value of a 32 bit signed integer is 2^31-1, namely 2147483647. Now, if you assign a higher value to an Int variable the behaviour is quite unexpected, try and see what i actually contains.
BTW, what do you mean by "infinite loop"? Does the program crash or does it never end executing?