malloc/free、ダングリングポインタ、メモリリーク、callocの理解度を確認しましょう。
int *p = (int *)malloc(sizeof(int) * 3); p[0] = 10; p[1] = 20; p[2] = 30; printf("%d\n", p[1]); free(p);
malloc(sizeof(int)*3) で int 3個分のヒープ領域を確保。p[1] は2番目の要素 = 20。int *p = (int *)malloc(sizeof(int)); *p = 42; free(p); printf("%d\n", *p);
p = NULL; にするのが安全です。void func(void) { int *p = (int *)malloc(sizeof(int) * 100); *p = 42; // free(p) を忘れた }
int *a = (int *)calloc(5, sizeof(int)); printf("%d %d %d\n", a[0], a[2], a[4]); free(a);
calloc は malloc と違い、確保した領域を0で初期化します。