Search code examples
c++visual-c++visual-studio-debugging

Strange behavior with function strncpy?


In my project,I have met these strange problem with strncpy. I have checked the reference. But the function strncpy behavior make me confused. In this function, when it runs to strncpy(subs,target,term_len);

status of variables

While I don't know why there is two blanks after the string?!!! It is a big project, I cannot paste all the code here. Following is just a piece. All my code is here.

char* subs = new char[len];
while(top<=bottom){
    char* term = m_strTermTable[bottom].strterm;
    int term_len = strlen(term);
    memset(subs,'\0',len);
    strncpy(subs,target,term_len);
    int subs_len = strlen(subs);
    int re = strcmp(subs,term);
    if (re == 0)
    {
        return term_len;
    }
    bottom--;
}
delete[] subs;

Solution

  • strncpy does not add a terminating null byte if the source string is longer than the maximum number of characters (i.e. in your case, that would be if strlen(target) > term_len holds). If that happens, subs may or may not be null terminated correctly.

    Try changing your strncpy call to

    strncpy(subs, target, term_len-1);
    

    so that even if strncpy doesn't add a terminating null byte, subs will still be null-terminated correctly due to the previous memset call.

    Now, that being said - you could avoid using a separate subs buffer altogether (which leaks anyway in case the control flow gets to the return statement) by just using strncmp as in

    while(top<=bottom) {
        char* term = m_strTermTable[bottom].strterm;
        int term_len = strlen(term);
        if (strncmp(term, target, term_len) == 0) {
            return term_len;
        }
        bottom--;
    }