C 动态内存管理
1:void *malloc(size_t size) 分配所需的内存空间,并返回一个指向它的指针。
char *str; str = (char *)malloc(15); strcpy(str, "hello world"); printf("str = %s\n", str); free(str); //数组 char *arr; arr = (char *)malloc(sizeof(char[4])); if (arr) { for (int n = 0; n < 3; n++) { arr[n] = 'S'; } arr[3] = '\0'; } printf("str = %s\n", arr); free(arr);
2:calloc 分配所需的内存空间,并返回一个指向它的指针
char *str1; str1 = (char *)calloc(4, sizeof(char)); if (str1) { for (int n = 0; n < 3; n++) { str1[n] = 'S'; } str1[3] = '\0'; } printf("str = %s\n", str1); free(str1);
3: void *realloc(void *ptr, size_t size) 重新调整之前调用 malloc 或 calloc 所分配的 ptr 所指向的内存块的大小.
4:void free(void * ptr);释放以前由calloc,malloc,realloc 或者aligned_alloc分配的空间.

浙公网安备 33010602011771号