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;
}
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.
Examination Categories
- SSC Exams
- Banking Exams
- Teaching Exams
- Civil Services Exams
- Railways Exams
- Engineering Recruitment Exams
- Defence Exams
- State Government Exams
- Police Exams
- Insurance Exams
- Nursing Exams
- Other Government Exams
- NRA CET
- PG Entrance Exams
- Campus Placement
- MBA Entrance Exams
- CUET and UG Entrance
- Judiciary Exams
- Regulatory Body Exams
- Software Development