使用 free() 释放动态内存
Free dynamic memory with free()
#include <stdlib.h>
#include <stdio.h>
int main() {
char **last_names;
// last_names has been assigned a char * array of length 4. Each element of the array has
// been assigned a char array of length 20.
//
// All of these memory has been allocated on the heap.
// Free all of the allocated memory (hint: 5 total arrays).
return 0;
}
我知道 free() 方法,这是我的方法;
free(*last_names);
free(last_names);
但事实并非如此。任何帮助将不胜感激
根据您对代码的描述猜测,您的内存分配将是:
last_names = malloc(4 * sizeof(char*));
for (int i = 0; i < 4; i++)
last_names[i] = malloc(20 * sizeof(char));
所以释放应该按如下方式进行:
for (int i = 0; i < 4; i++)
free(last_names[i]);
free(last_names);
#include <stdlib.h>
#include <stdio.h>
int main() {
char **last_names;
// last_names has been assigned a char * array of length 4. Each element of the array has
// been assigned a char array of length 20.
//
// All of these memory has been allocated on the heap.
// Free all of the allocated memory (hint: 5 total arrays).
return 0;
}
我知道 free() 方法,这是我的方法;
free(*last_names);
free(last_names);
但事实并非如此。任何帮助将不胜感激
根据您对代码的描述猜测,您的内存分配将是:
last_names = malloc(4 * sizeof(char*));
for (int i = 0; i < 4; i++)
last_names[i] = malloc(20 * sizeof(char));
所以释放应该按如下方式进行:
for (int i = 0; i < 4; i++)
free(last_names[i]);
free(last_names);