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?
- A. Nothing, because malloc always checks overflow
- B. The array is silently zeroed
- C. The multiplication becomes a floating-point value
- 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
- A malloc'd block of 16 bytes is written past its end by 4 bytes. What is the correct description?
- Which function call allocates storage for an array of 100 doubles, all set to 0.0, in one step?
- A function gets a pointer to a linked list and must keep the list unchanged but needs to walk it twice. Which kind of pointer parameter is…
- A program keeps 10^5 small objects in a free list of pointers. Which operation is O(1) per object?
- int arr = malloc(5 sizeof arr); for (int i = 0; i < 5; i++) arr[i] = i i; int q = arr + 2; printf("%d", q[1]); What is printed?
- struct N { int v; struct N next; } a = NULL; for (int i = 1; i <= 3; i++) { struct N n = malloc(sizeof n); n->v = i; n->next = a; a = n; }…