C on a 16-bit platform — what does sizeof(p) print for an int* allocated with malloc?\n\n#include<stdio.h>\n#include<stdlib.h>\n\nint main()\n{\n int p = (int ) malloc(20);\n printf("%d\n", (int) sizeof(p));\n free(p);\n return 0;\n}\n\nAssume a classic 16-bit memory model.

Difficulty: Easy

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

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion