ProgrammingVery hard

A program allocates an int array of size n with malloc(n * sizeof(int)). For n = 2^31, on a platform with 32-bit size_t, what can go wrong?

  1. A. Nothing, because malloc always checks overflow
  2. B. The array is silently zeroed
  3. C. The multiplication becomes a floating-point value
  4. D. n * sizeof(int) can wrap in size_t, so the allocation size is wrong unless the code checks the multiplication

Correct answer: D. n * sizeof(int) can wrap in size_t, so the allocation size is wrong unless the code checks the multiplication

On a 32-bit size_t the product 2^33 wraps, giving a small allocation and an out-of-bounds write later. calloc or an explicit overflow check avoids this.

More C Programming questions

Exams that ask this topic