Discussion
What will be the output of the following C code?
#include <stdio.h>
int main()
{
char str[10] = "hello";
char *str1 = "world";
strncat(str, str1, 9);
printf("%s", str);
}
Answer: A
Correct answer: Undefined behaviour
Count the bytes: str is 10 long and already holds hello. strncat appends up to 9 characters from world - all five - and then adds a terminating null, so it writes to indices 5 through 10. Index 10 is one past the end of the array, so this is a buffer overflow and the behaviour is undefined; it may well print helloworld, but only by accident. The n in strncat limits the source, not the destination, so it is no protection here: char str[11] is what the call needs.
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