Machine-translated by Google. Questions are authored in English.
Top

Discussion

What will be the output of the program (16-bit platform)?

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int *p;
    p = (int *)malloc(20);
    printf("%d\n", sizeof(p));
    free(p);
    return 0;
}

 

  • A.4
  • B.2
  • C.7
  • D.Garbage value

Answer: B

Correct answer: 2

sizeof(p) gives the size of the pointer, not of the 20 bytes it points to. On the 16-bit platform the question specifies, a near pointer holds a 16-bit offset and occupies 2 bytes.

The same expression gives 4 on a 32-bit build and 8 on a 64-bit one, which is why the platform has to be stated for the question to have an answer. There is no portable way to ask how large an allocated block is; a program that needs to know must record the size itself.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.