释放已分配给char指针(字符串)数组的内存.我必须释放每个字符串还是仅释放"main"字符串?指针? [英] Freeing memory which has been allocated to an array of char pointers (strings). Do I have to free each string or just the "main" pointer?

查看:278
本文介绍了释放已分配给char指针(字符串)数组的内存.我必须释放每个字符串还是仅释放"main"字符串?指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数,该函数需要一个指向char **的指针,并用字符串(我猜是字符串数组)填充它. * list_of_strings *是在函数内部分配的内存.

I have a function that takes a pointer to a char ** and fills it with strings (an array of strings I guess). *list_of_strings* is allocated memory inside the function.

char * *list_of_strings = NULL;

/* list_of_strings malloc'd inside function */
fill_strings_with_stuff(&list_of strings);

use_list_for_something(list_of_strings);

/* Now how do I free it all? */

使用字符串后如何释放内存?如果我打电话

How would I go about freeing the memory after I've used the strings? If I call

free(list_of_strings);

那不只是释放实际的指针,而不是释放每个字符串本身正在使用的内存吗?如何完全释放内存

won't that just free the actual pointers and not the memory each string itself was using? How do I completely free the memory

为清楚起见,该函数看起来像这样:

Just for clarity the function looks something like this:

fill_strings_with_stuff(char *** list)
{
    *list = malloc(AMOUNT);

    for (i = 0; i < SOMETHING; i++) {
        *(list + i) = malloc(LINE_LEN);
        *(list + i) = some_string_from_somewhere
    }

    /* ... */

}

推荐答案

那不只是释放实际的指针,而不是释放每个字符串本身正在使用的内存吗?

won't that just free the actual pointers and not the memory each string itself was using?

是的.

我如何完全释放内存

How do I completely free the memory

通过遍历数组并在 释放数组本身之前一一释放每个字符串.例如

By looping through the array and freeing each string one by one before freeing up the array itself. E.g.

for (i = 0; i < SOMETHING; i++) {
    free(list[i]);
}
free(list);

这篇关于释放已分配给char指针(字符串)数组的内存.我必须释放每个字符串还是仅释放"main"字符串?指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆