私のプログラムでは、ファイルを開いて "Hello world"と書いています。私は 'fname'変数を設定するためにsnprintf()を使用しています。この後、gdbをa.outに置き、文字列 'fname'を出力します。私は割り当てられていない文字列 'fname'に余分な文字がたくさんあることがわかります。これらの余分な文字はどこから来ていますか?誰でも助けてくれますか?なぜsnprintf()は余分な文字を書きますか?
3 int main(void)
4 {
5 FILE *debug_fp = NULL;
6 char fname[100];
7
8 snprintf(fname, 100, "./my_debug_%d", getpid());
9 debug_fp = fopen(fname, "w");
10 fprintf(debug_fp, "%s", "Hello world");
11 return 0;
12 }
gdbの出力:
(gdb) b test.c:10
Breakpoint 1 at 0x4005be: file test.c, line 10.
Breakpoint 1, main() at test.c:10
10 fprintf(debug_fp, "%s", "Hello world");
(gdb) p fname
$1 = "./my_debug_16178\000\000\000\000\000\000\000\000\300\313Ab:\000\000\000\360\[email protected]\000\000\000\000\000\063\[email protected]\000\000\000\000\000\001\000\000\000\000\000\301\000'\[email protected]", '\000' <repeats 13 times>"\300, \313Ab:\000\000\000\360\[email protected]", '\000' <repeats 13 times>"\260, \343\377\377"
(gdb) q
ありがとうございます。
デバッガには、何かに割り当てられているかどうかにかかわらず、 'fname'配列に割り当てられた' 100'文字がすべて表示されます。 – mvidelgauz
'fprint'に100個の文字を生成するよう明示しました。それはまさにそれでした。 – Koshinae
@Koshinaeいいえ、「snprintf」のsize引数は、「最大でも**サイズのバイトを書く」ことを意味します。 – cnicutar