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