1

strcat() 関数に問題があります。その機能の仕組みを教えてください。

char a[] = "AT";
char x[] = "KA";
char y = 'X';
sen(a);
s = strcat(a, "+CMGF=");
sen(s);
s = strcat(s, "\r\n");
sen(s);
s = strcat(s, &y);
sen(s);
getch();
return 0;

S はグローバル文字ポインターであり、 sen() は、含まれている文字列のデータを出力するためだけの関数です。s の最終的な値は "AT+CMGF=\r\nXKA" です。

コードを書いていませんが、s の最後に x 配列を自動的に追加します。

なぜそうなのですか?説明してください

4

2 に答える 2

4

あなたは未定義の行動の領域にいます。より具体的には、次のことを行っています。

char a[] = "AT";
char x[] = "KA";
char y = 'X';
s = strcat(a, "+CMGF="); // a is a constant string, so this is NOT fine.  You should be calling s = strcat(s, a) and then s = strcat(s, "+CMGF=")
s = strcat(s, "\r\n"); // "\r\n" = "\r\n\0", so it is also fine
s = strcat(s, &y); // y is a char, and is NOT null-terminated, so it is NOT fine

たまたま、使用しているコンパイラがメモリのセクションに並べて配置されyxいるためstrcat、最初のヌルターミネータが見つかるまで動作しています。sそして、これはすべて、これらの連結をすべて保持するのに十分なスペースが割り当てられていることを前提としています (そうでない場合は、未定義の動作の別の領域にいることになります)。

既知の問題をすべて修正するには:

char s[100] = {0}; // showing declaration of s of sufficient size
char a[] = "AT";
char x[] = "KA";
char y[] = "X";

sen(s); // shows empty string
s = strcat(s, a); // append a to empty s
s = strcat(s, "+CMGF="); // append "+CMGF=" to the end of new s
sen(s); // will now show "AT+CMGF="
s = strcat(s, "\r\n"); // add "\r\n"
sen(s); // will now show "AT+CMGF=\r\n"
s = strcat(s, y); // append y
sen(s); // will now show "AT+CMGF=\r\nX"
于 2013-09-16T18:49:23.083 に答える