Search code examples
c++mfcformatcstring

What is the internal structure of an object of the (EDIT: MFC) CString class?


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?


Solution

  • 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:

    #define DEST_STR_LEN 10
    
    char dest_str[DEST_STR_LEN + 1];  // +1 for the null
    strncpy(dest_str, src_str, DEST_STR_LEN);
    dest_str[DEST_STR_LEN] = '\0';
    

    If src_str is more than DEST_STR_LEN characters long, dest_str will be a properly-terminated string of DEST_STR_LEN characters. If src_str is shorter than that, strncpy() will put a null terminator somewhere within dest_str, so the null at the very end is irrelevant and harmless.