次のプログラムで、文字列のコピーを表示しようとしています。でも、間違いが含まれているため正く動きません。

どこが間違っているのか分かりますか?
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!

ええと、まず
malloc()
でコピー先のメモリーを確保して、次にstrncpy()
で文字列をコピーしてるってことですね。

でも、コピーした文字列が表示されないのよ。

printf()
を実行するタイミングに注目してみましょう。