Search code examples
cnullintegertermination

C - Random characters after using strncpy() function


I have the following program in C:

The main problem with the program is that after I perform the copy operation, a number of rubbish characters are displayed after the letters copied. I know this is because the destination variable is NOT properly null-terminated. However, if you inspect the code carefully, I am performing null-termination. Why is the problem still there?


Solution

  • strncpy does not guarantee that your destination string will be null-terminated after the copy. My approach would be to:

    destination[ nob ] = '\0';