C on a 16-bit platform — what does sizeof(p) print for an int* allocated with malloc?
#include
#include
int main()
{
int p = (int ) malloc(20);
printf("%d
", (int) sizeof(p));
free(p);
return 0;
}
Assume a classic 16-bit memory model.
-
A4
-
B2
-
C8
-
DGarbage value
Answer
Correct Answer: 2
Explanation
Introduction / Context:This problem tests platform awareness: sizeof on a pointer reports the size of the pointer type itself, which varies by architecture and memory model. On classic 16-bit DOS small/medium models, data pointers are near (2 bytes).
Given Data / Assumptions:
- Target is a 16-bit environment like Turbo C small/medium model.
- p is declared as int (a data pointer).
- sizeof(p) is evaluated and printed as an int.
Concept / Approach:sizeof(p) depends only on the pointer type, not on the allocated size. On many 16-bit compilers, near data pointers are 2 bytes. Therefore sizeof(int) is 2 in those models. (Far/huge models may differ, but the question specifies a 16-bit platform context where 2 is the canonical teaching answer.)
Step-by-Step Solution:
1) Identify pointer category: near data pointer.2) On 16-bit near model, sizeof pointer = 2 bytes.3) Hence the program prints 2.Verification / Alternative check:Switching to a 32-bit or 64-bit compiler typically yields 4 or 8 respectively for sizeof(void*) and data pointers, confirming the platform dependence.
Why Other Options Are Wrong:
- 4/8: Sizes found on 32/64-bit systems, not classic 16-bit near model.
- Garbage value: sizeof is compile-time and deterministic.
Common Pitfalls:Confusing allocated block size with pointer size. sizeof(p) is not related to malloc(20).
Final Answer:2