I need to strncpy() (effectively) from a (Edit: MFC) CString object to a C string variable. It’s well known that strncpy() sometimes fails (depending on the source length **EDIT and the length specified in the call) to terminate the dest C string correctly. To avoid that evil, I’m thinking to store a NUL char inside the CString source object and then to strcpy() or memmove() that guy.
Is this a reasonable way to go about it? If so, what must I manipulate inside the CString object? If not, then what’s an alternative that will guarantee a properly-terminated destination C string?
strncpy()only “fails” to null-terminate the destination string when the source string is longer than the length limit you specify. You can ensure that the destination is null-terminated by setting its last character to null yourself. For example:If
src_stris more thanDEST_STR_LENcharacters long,dest_strwill be a properly-terminated string ofDEST_STR_LENcharacters. Ifsrc_stris shorter than that,strncpy()will put a null terminator somewhere withindest_str, so the null at the very end is irrelevant and harmless.