I thought that the maximum index for an array is a signed int, 2147483647. However reading online, I found posts stating that for a 32 bit system an array can have 4294967295 elements, unsigned int. And for a 64 bit system, an array can have 2^64 elements, 18446744073709551616.
When I tried to compile and run the following program, I got a warning:
[Warning] integer overflow in expression [-Woverflow]
#include <iostream>
using namespace std;
int main()
{
int maxindex = 2147483647+1;
char* p = new char [maxindex];
for(int i = 0; i < maxindex; i++)
{
p[i] = 65;
}
cout<<"Value at index "<<maxindex-1<<" is "<<p[maxindex-1]<<endl;
delete[] p;
return 0;
}
When I ran the program, it terminated immediately:
terminate called after throwing an instance of 'std::bad_alloc' what(): std::bad_alloc
This application has requested the Runtime to terminate it in an unusual way. Please contact the application's support team for more information.
If I change int maxindex = 2147483647+1;
to int maxindex = 2147483647;
the program runs with no problems. What am I doing wrong and is the limit for new[] index 2^64, 18446744073709551616, or 2147483647?