Unterminated string

An operation may result in a string without a terminating null character.

Some forms of the string copy and concatenate operations like strncpy impose a limit on the total number of characters that will be moved to the destination address. If you attempt to move more characters than the destination can hold, the size limit will prevent the destination from overflowing, but can result in a string value that is not null terminated. Use of a string that is not null terminated can have unpredictable (and usually bad) consequences.

After using one of these string move operations, you should assign a null to the last character in the destination. This guarantees that the result is null terminated.

ID

Observation

Description

1

Call site

The call to the string function

2

Declaration

The place the string was declared

Examples


#include <string.h>

char * safer_strncpy(char *dest, const char *src, size_t count)
{
    strncpy(dest, src, count);
    dest[count - 1] = 0; // guarantees result is null terminated
    return dest;
}

int main(int argc, char **argv)
{
    char buff[10];
    
    // copy from source longer than destination
    safer_strncpy(buff, "123456789012", sizeof(buff));
    printf("%s\n", buff);
    
    strncpy(buff, "123456789012", sizeof(buff));
    printf("%s\n", buff); // might print a LOT of data
    return 0;
}
        

Copyright © 2010, Intel Corporation. All rights reserved.