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;
}
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.
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