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
(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
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.