C dynamic allocation — how many bytes are reserved by this call?\n\n#include<stdio.h>\n#include<stdlib.h>\n\nint main()\n{\n int p;\n p = (int ) malloc(256 * 256);\n if (p == NULL)\n printf("Allocation failed");\n return 0;\n}\n\nAssume the request succeeds. How many bytes does malloc attempt to reserve?

Difficulty: Easy

Correct Answer: 65536

Explanation:


Introduction / Context:
This problem checks if you can compute the size argument passed to malloc and interpret it as bytes reserved, independent of the pointer's base type. The cast to int does not change the number of bytes requested.


Given Data / Assumptions:

  • malloc is called with 256 * 256.
  • No sizeof is involved in the multiplication.
  • We assume the allocation succeeds for the purpose of counting bytes.


Concept / Approach:
malloc receives a size in bytes. The expression 256 * 256 equals 65536, so malloc attempts to reserve exactly 65536 bytes. The type of p (int) only affects how you interpret the memory later, not the number of bytes allocated.


Step-by-Step Solution:

1) Compute size = 256 * 256 = 65536.2) malloc requests that many bytes from the heap.3) p points to the first byte of the reserved block (cast to int*).


Verification / Alternative check:
To reserve space for N ints portably, use malloc(N * sizeof *p). Here the code requests a raw byte count; counting bytes confirms the value 65536.


Why Other Options Are Wrong:

  • Allocation failed / Error / No output: These describe runtime outcomes, not the byte count requested by the code.


Common Pitfalls:
Confusing number of elements with number of bytes or assuming sizeof(int) is implicitly applied. Always multiply by sizeof when allocating typed arrays.


Final Answer:
65536

More Questions from Memory Allocation

Discussion & Comments

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