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

Discussion

Point out the error of the following code −

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
   char* ptr;
   *ptr = (int*)malloc(30);
   strcpy(ptr, "ABC");
   printf("%s", ptr);
   free(ptr);
}

 

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

Answer: B

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

The asterisk is in the wrong place. ptr is a char *, so *ptr is a single char, and the line attempts to assign a pointer to it. The types are incompatible and the address is discarded even if the compiler is persuaded to accept it.

The line should read ptr = malloc(30);. Everything after it then depends on this error: strcpy writes through a pointer that was never given a valid address, which is undefined behaviour.

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

Post your comment

Please log in or register to post a comment.