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

Discussion

What is the Error of this program?

#include <stdio.h>
#include <stdlib.h>
int main()

{
     char *ptr;
     *ptr = (char)malloc(30);
     strcpy(ptr, "RAM");
     printf("%s", ptr);
     free(ptr);
     return 0;
}

 

  • A.Error: in strcpy() statement.
  • B.Error: in *ptr = (char)malloc(30);
  • C.Error: in free(ptr);
  • D.No error

Answer: B

Correct answer: Error: in *ptr = (char)malloc(30);

Two things are wrong on that one line. *ptr is a single char, not a pointer, so the assignment target is wrong; and the cast to (char) converts the returned address to a single character, discarding all but its lowest byte.

The line should read ptr = malloc(30);. Everything downstream then depends on it: strcpy writes through a pointer that never received a valid address, which is undefined behaviour and will usually fault.

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

Post your comment

Please log in or register to post a comment.