【C言語】
文字列終端のヌル文字’\0’を
忘れると暴走する

■strcpyでヌル文字を忘れる

#include <stdio.h>
#include <string.h>

int main(void){
    char    pre[] = "前前";
    char    dsname[4];
    char    aft[] = "後後";

    strcpy(dsname,"1234");//メモリ破壊
    printf("%s:%s:%s\n",pre,dsname,aft);
}

warning: ‘strcpy’ will always overflow; destination buffer has size 4, but the source string has length 5 (including NUL byte)
[-Wfortify-source]

dsname[]4byteの領域に
“abcd”+ヌル文字’\0’=5byteコピーするので
メモリ破壊します。


■strncpyでヌル文字を忘れる

#include <stdio.h>
#include <string.h>

int main(void){
    char    pre[] = "前前";
    char    dsname[4];
    char    aft[] = "後後";

    strncpy(dsname,"1234",4);//¥0欠損
    printf("%s:%s:%s\n",pre,dsname,aft);
}

warning: ‘strncpy’ output truncated before terminating nul copying 4 bytes from a string of the same length [-Wstringop-truncation]

dsname[]4byteの領域に
“abcd”=4byteコピーするのでヌル文字’\0’がコピーされません。
ヌル文字が無いのでprintfで暴走します。

■sprintfでヌル文字を忘れる

//gcc -fsanitize=address
#include <stdio.h>
#include <string.h>

int main(void){
    char    pre[] = "前前";
    char    dsname[4];
    char    aft[] = "後後";

    sprintf(dsname,"1234");//メモリ破壊
    printf("%s:%s:%s\n",pre,dsname,aft);
}

warning: ‘sprintf’ writing a terminating nul past the end of the destination
[-Wformat-overflow=]

strcpy同様
dsname[]4byteの領域に
“abcd”+ヌル文字’\0’=5byteコピーするので
メモリ破壊します。

■snprintfでヌル文字を忘れる

#include <stdio.h>
#include <string.h>

int main(void){
    char    pre[] = "前前";
    char    dsname[4];
    char    aft[] = "後後";

    snprintf(dsname,4,"1234");//最後の4が欠損
    printf("%s:%s:%s\n",pre,dsname,aft);
}

warning: ‘snprintf’ output truncated before the last format character
[-Wformat-truncation=]

sizeで4byteを指定しているので
“abcd”ではなくて
“abc”+’\0’の4byte書き込まれます。

■要素数を指定してヌル文字を忘れる

#include <stdio.h>
#include <string.h>

int main(void){
    char    pre[] = "前前";
    char    dsname[4]="1234";//要素数[4]をわざわざ書く
    char    aft[] = "後後";

    printf("%s:%s:%s\n",pre,dsname,aft);
}

初期値”1234”があるのに、dsname[4]と要素数4を記述してしまったため
ヌル文字が入る隙間がありません。
ヌル文字が無いのでprintfで暴走します。

参考:

STR11-C. 文字列リテラルで初期化される文字配列のサイズを指定しない

https://www.jpcert.or.jp/sc-rules/c-str11-c.html