Thursday, October 27, 2005

integer overflow in operator new[]

Does it come as a surprise that array allocation can cause an integer overflow? Not really. My tests with GCC 4 on Linux show that many array allocation operations are affected:

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.