malloc / free

1. 完整例子

C
1#include <stdio.h>
2#include <stdlib.h>
3 
4int main(void) {
5 int n = 4;
6 int *p = (int *)malloc(n * sizeof(int));
7 if (!p) {
8 printf("oom\n");
9 return 1;
10 }
11 for (int i = 0; i < n; i++) p[i] = i * i;
12 printf("%d\n", p[3]);
13 free(p);
14 p = NULL;
15 return 0;
16}

2. 拆解