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

Discussion

Point out the error in the following 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);

The line assigns to *ptr - a single character - rather than to ptr, and casts the returned address to (char), which throws away everything but its lowest byte.

It should read ptr = malloc(30);. The strcpy that follows is then writing through a pointer that holds no valid address, so it is the line most likely to crash - but the cause lies in the allocation line above it, which is what the question asks for.

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

Post your comment

Please log in or register to post a comment.