タンブラー?

Big Sky

1月 13 '12

勝手に添削 - strncpyの罠

まぁソート関数自身の問題じゃないので控えめに。

strncpyは必ず \0 で埋めてくれるとは限らない。 404 Blog Not Found:algorithm - bucketsort.[ch] - 汎用かつlibcの*sortより高速な

dankogai/c-bucketsort - GitHub http://blog.livedoor.jp/dankogai/archives/51764911.html dankogai/c-bucketsort - GitHub

bucketsort - bucket sort that can be used for general purpose https://github.com/dankogai/c-bucketsort strncpy(3)のmanページにはこう書いてある。

The strcpy() function copies the string pointed to by src, including the terminating null byte (‘\0’), to the buffer pointed to by dest. The strings may not overlap, and the destination string dest must be large enough to receive the copy.

The strncpy() function is similar, except that at most n bytes of src are copied. _Warning: If there is no null byte among the first n bytes of src, the string placed in dest will not be null-terminated._ なので… # ./bucketsort README とかするとNULストップしてないバッファで画面が賑やかになり、時にはけたたましいビープ音で心躍る。

サンプルプログラムの仕様が最終行の改行コードなしでも動く様にすべきなのかどうなのかが分からないので diff —git a/main.c b/main.c
index 67e4e00..48391b4 100644
—- a/main.c
+++ b/main.c
@@ -74,6 +74,7 @@ int main(int argc, char **argv)
        if (!lines[lcur])
            EXIT(“malloc failed”);
        strncpy(lines[lcur], buf, slen - 1);    // do not copy \n
+       lines[lcur][slen - 1] = 0;
     }
     size_t i;
     // for (i = 0; i

1リアクション

  1. mattnの投稿です