免费动态内存(免费)

时间:2017-06-02 01:38:08

标签: c memory dynamic 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);

但事实并非如此。任何帮助将不胜感激

1 个答案:

答案 0 :(得分:0)

根据您对代码的描述进行猜测,您的内存分配将是:

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);