0 0 votes Programming in C programming programming-in-c pointers + – Ysh 1 211 views answer comment Share Follow Print See all 2 Comments 2 2 Comments reply Ysh 1 commented Feb 23 reply Follow flag Q]Is the ans : A0 or A followed by garbage values ? 0 0 replyShare Ysh 1 commented Sep 28 reply Follow flag The program in the linked question is: #include <stdio.h> #include <stdlib.h> int main() { int count = 0; char *p = (char *)malloc(sizeof(char)); *p = 65; printf("%c", *p); p = realloc(p, 4 * sizeof(char)); *p = 256; printf("%d", *(int *)p); return 0; } Step-by-step 1. malloc(sizeof(char)) p = malloc(1); One byte is allocated. 2. Store 65 *p = 65; printf("%c", *p); 65 corresponds to 'A' in the usual ASCII environment. So the first output is: A 3. realloc p = realloc(p, 4); The allocated block becomes 4 bytes. The old byte's value is preserved; the additional bytes do not have meaningful initialized values. 4. Critical statement *p = 256; p is a char *, so the value is converted to char. The exact resulting value depends on the implementation; it is not something you can safely treat as the integer 256 stored in 4 bytes. 5. Then: printf("%d", *(int *)p); This is the real problem. You stored/accessed the allocated object through a char lvalue, and then attempt to access it through an int lvalue: char object ---> accessed as int That violates the C effective-type/strict-aliasing rules, producing undefined behavior. Also, the code assumes the 4-byte allocation is enough for an int, which is not guaranteed by the C standard. Therefore The answer is not A0 and it is also not A + garbage values The only predictable part is: A After that, the program has undefined behavior, so the complete output is not defined. It could print A0, A followed by some other value, crash, or behave differently. GATE takeaway Whenever you see: char *p = malloc(...); ... printf("%d", *(int *)p); don't automatically assume "read the bytes as an integer." Check: 1. Effective type / strict aliasing 2. Alignment 3. Enough allocated bytes 4. Object representation / initialization Here, undefined behavior is the decisive point. 0 0 replyShare Please log in or register to add a comment.