Test your understanding of malloc/free, dangling pointers, memory leaks, and 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) allocates space for 3 ints on the heap. p[1] is the second element = 20.int *p = (int *)malloc(sizeof(int)); *p = 42; free(p); printf("%d\n", *p);
p = NULL; right after free.void func(void) { int *p = (int *)malloc(sizeof(int) * 100); *p = 42; // forgot free(p) }
free loses the pointer, so the allocated memory can never be returned to the heap.int *a = (int *)calloc(5, sizeof(int)); printf("%d %d %d\n", a[0], a[2], a[4]); free(a);
malloc, calloc zero-initializes the allocated memory.calloc whenever zero-initialization is desired.