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

Discussion

What will be the output of the following C code?

#include <stdio.h>
    #include <string.h>
    int main()
    {
        char *str = "hello, world";
        char str1[9];
        strncpy(str1, str, 9);
        printf("%s %d", str1, strlen(str1));
    }

 

  • A.hello, world 11
  • B.hello, wor 9
  • C.Undefined behaviour
  • D.Compilation error

Answer: C

Correct answer: Undefined behaviour

strncpy copies at most n characters and adds a terminating null only if the source is shorter than n. Here the source has 12 characters and n is 9, so all nine bytes of str1 are filled with hello, wo and no null is written. Passing that to printf("%s") and strlen reads past the end of the array - undefined behaviour.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.