Hi guys , I have just read the article about dynamic memory in the documentation and tried to compile the code provided with it . But when I enter a large number that the required memory can't be allocated it gives me Debug Error , in spite of using nothrow Method
Here is the code
// rememb-o-matic
#include <iostream>
#include <new>
usingnamespace 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 == 0)
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;
}
I use Windows 7 ultimate 64 bit & Visual studio 2010
int main ()
{
int i,n;
// Init the value of p to null
int * p(0); // <--------- Look here
// etc...
return 0;
}
EDIT: Never mind, nothrow should return a null if failed.
EDIT: What is the size of the allocation you are trying to allocated to make it fail? The largest value i (signed int) can hold is 2147483647 bytes just over 2Gbytes.
Like if I enter:
./a.out
Enter: 4000000000
i: 134513706
I don't think you are getting the size of the number that you think. Make i a 64-bit number.
1 2 3 4
// Add
#include <stdint.h>
// And make i
uint64_t i(0);