Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
文字列をコピーするためにこれが好きだとします。
char str[] = ""; char *str2 = "abc"; strcpy(str, str2); printf("%s", str); // "abc" printf("%d", strlen(str)); // 3
次に、未定義の動作が発生したり、プログラムが失敗したりしないのはなぜですか。そのようにすることの欠点は何ですか?
スタック上の str に割り当てられたメモリ空間を超えて書き込んでいます。str に適切な量のスペースがあることを確認する必要があります。あなたが言及した例では、a、b、および c に加えて文字列を終了するための null 文字のスペースが必要なので、このコードは機能するはずです。
char str[4]; char *str2 = "abc"; strcpy(str, str2); printf("%s", str); // "abc" printf("%d", strlen(str)); // 3