size_t large_n
= std::numeric_limits<size_t>::max()
/ 0x10 + 2;
struct A { int a, b, c, d; }; // 0x10 bytes
void test() {
{
A * arr = new A[large_n];
// succeeds, but what does it mean?
arr[5000].a = 10;
}
{
// a clear overflow
A * arr = (A*) malloc(large_n * sizeof(A));
}
{
A * arr = (A*) calloc(large_n, sizeof(A));
// SEGFAULT
arr[5000].a = 10;
}
{
// bad_alloc - correct behavior
vector<a> arr(large_n);
}
}
Notice, that vector<> behaves as expected. Again C++ standard library shows its superiority to the conventional "do it yourself" methods. This is just another reason to use vector<> everywhere where an array is needed.
No comments:
Post a Comment