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

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

 

  • A.helloworld
  • B.Undefined behaviour
  • C.helloworl
  • D.hellowor

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.