操作で、文字列がヌルで終了していない可能性があります。
strncpy などの文字列のコピーや連結操作によっては、デスティネーション・アドレスに移動される文字数に制限があります。デスティネーションで保持できる文字数以上の文字を移動しようとすると、サイズ制限によりデスティネーションのオーバーフローは回避されますが、文字列はヌルで終了されません。ヌルで終了していない文字列の使用は、予測できない (通常は悪い) 結果をもたらします。
次のいずれかの文字列の移動操作を行う場合は、デスティネーションの最後の文字にヌルを追加して、 必ずヌルで終了されるようにしてください。
ID |
問題箇所 |
説明 |
---|---|---|
1 |
呼び出し位置 |
文字列関数の呼び出し |
2 |
宣言 |
文字列が宣言された場所 |
#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; }
© 2010 Intel Corporation. 無断での引用、転載を禁じます。