次のプログラムで、文字列のコピーを表示しようとしています。でも、間違いが含まれているため正く動きません。
![](/wp-content/include/images/avatar/teacher/5.png)
どこが間違っているのか分かりますか?
main.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
char text[] = "Hello!";
char *pCopyOfText = malloc(sizeof(text));
if (pCopyOfText) {
strncpy(pCopyOfText, text, sizeof(text));
free(pCopyOfText);
}
printf("%s\n", pCopyOfText);
return EXIT_SUCCESS;
}
期待される実行結果
Hello!
![](/wp-content/include/images/avatar/student/7.png)
ええと、まず
malloc()
でコピー先のメモリーを確保して、次にstrncpy()
で文字列をコピーしてるってことですね。
![](/wp-content/include/images/avatar/teacher/9.png)
でも、コピーした文字列が表示されないのよ。
![](/wp-content/include/images/avatar/teacher/7.png)
printf()
を実行するタイミングに注目してみましょう。