C program printing weird characters

后端 未结 1 427
灰色年华
灰色年华 2021-01-17 00:00

I have a program that reads the content of a file and saves it into buf. After reading the content it is supposed to copy two by two chars to an array. This cod

相关标签:
1条回答
  • 2021-01-17 00:56
    1. (char*)malloc(2*sizeof(char)); change to malloc(3*sizeof*buffer); You need an additional byte to store the terminating null character which is used to indicate the end-of-string. Aslo, do not cast the return value of malloc(). Thanks to unwind

    2. In your case, with strncpy(), you have supplied n as 2, which is not having any scope to store the terminating null byte. without the trminating null, printf() won't be knowing where to stop. Now, with 3 bytes of memory, you can use strcpy() to copy the string properly

    strncpy() will not add the terminating null itself, in case the n is equal to the size of supplied buffer, thus becoming very very unreliable (unlike strcpy()). You need to take care of it programmatically.

    check the man page for strncpy() and strcpy() here.

    0 讨论(0)
提交回复
热议问题