In an internal email, someone wrote malloc(width * height * sizeof(int)) to allocate an integer matrix of width x height. If you think carefully about this simple line of code, it's potentially dangerous.
Suppose you're providing a webpage which allows user to enter a matrix and then perform some compliated calculation. The matrix is entered as:
width height a00 a01 a02 ... a10 a11 a12 ....
If someone enters width = 32769 and height 32768, malloc(width * height * sizeof(int)) will allocate 32769 x 32768 * 4 bytes of memory. This value is is 32768 * 4 = 128 kb in 32-bit integer calculation due to overflow. Now all the data after width and height will be read into a much smaller heap memory block, corruptting heap. Your machine may be in the wrong hand now.?
What is needed a simple routine to make sure width * height * sizeof(int) does not overflow integer calculation and do not call malloc if they do.
bool CheckSize(uint width, uint height, uint uintsize)
{
if ((width == 0) || (height == 0) || (uintsize == 0))
return false;
uint limit = MAX_INT / unitsize;
limit /= height;
limit /= width;
return limit > 0;
}