C-释放指针数组是否还会释放它们指向的指针? [英] C - Does freeing an array of pointers also free what they're pointing to?

查看:108
本文介绍了C-释放指针数组是否还会释放它们指向的指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个指向结构的指针数组,这些结构每个都包含一个字符串,因此是这样的:

Say I have an array of pointers to structs that contain a string each and so for something like this:

printf("%s\n", array[0]);

输出为:

Hello.

如果我执行free(array),这将释放array[0]指向的内容吗? ("Hello.").

If I perform a free(array) will this free what array[0] is pointing to? ("Hello.").

我花了几个小时尝试手动释放每个元素,而我得到的只是崩溃.我希望这是一个捷径:/

I've spent hours attempting to manually free each element and all I get is crashes. I'm hoping this is a shortcut :/

推荐答案

这全部取决于数组的分配方式.我举个例子:

This all depends on how the array was allocated. I'll give examples:

示例1:

char array[10];
free(array);     // nope!

示例2:

char *array;
array= malloc(10);   // request heap for memory
free(array);         // return to heap when no longer needed

示例3:

char **array;
array= malloc(10*sizeof(char *));
for (int i=0; i<10; i++) {
    array[i]= malloc(10);
}
free(array);        // nope. You should do:

for (int i=0; i<10; i++) {
    free(array[i]);
}
free(array);

广告.示例1:array被分配在堆栈上(自动变量"),并且free无法释放.函数返回时将释放其堆栈空间.

Ad. Example 1: array is allocated on the stack ("automatic variable") and cannot be released by free. Its stack space will be released when the function returns.

广告.示例2:您使用malloc从堆中请求存储.当不再需要时,使用free将其返回到堆.

Ad. Example 2: you request storage from the heap using malloc. When no longer needed, return it to the heap using free.

广告.示例3:您声明了一个指向字符的指针数组.首先为数组分配存储空间,然后为每个数组元素分配存储空间以放置字符串.不再需要时,必须首先释放字符串(使用free),然后释放数组本身(使用free)

Ad. Example 3: you declare an array of pointers to characters. You first allocate storage for the array, then you allocate storage for each array element to place strings in. When no longer needed, you must first release the strings (with free) and then release the array itself (with free).

这篇关于C-释放指针数组是否还会释放它们指向的指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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