释放结构指针还会释放C中分配给结构内部的内存吗? [英] Will freeing a structure pointer also free the memory allocated inside of the structure in C?

查看:68
本文介绍了释放结构指针还会释放C中分配给结构内部的内存吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我具有以下结构:

For example I have this structure:

typedef struct{
    char *var = (char*)malloc(20*sizeof(char));
} EXAMPLE;

EXAMPLE *point = (EXAMPLE*)malloc(sizeof(EXAMPLE));

我的第一个问题是,仅当我为EXAMPLE指针分配内存时,才会分配结构内部分配的内存吗?

My first question is, will the memory allocated inside the structure only be allocated when I allocate memory for the EXAMPLE pointer?

第二个问题,当我使用free(point)时,也将释放为var分配的内存吗?

My second question, when I use free(point) will the memory allocated for var also be freed?

推荐答案

使用此结构:

typedef struct{
    char *var;
} EXAMPLE;

请记住,当您为结构分配空间时,您仅为char *指针分配空间.该指针仅指向其他地方的内存. free()结构时,您只是释放了char *指针,而不是它指向的实际内存.

Remember that when you allocate space for the struct, you're allocating space only for the char * pointer. This pointer just points to memory elsewhere. When you free() the struct, you're just freeing the char * pointer, not the actual memory that it points to.

这样,如果先创建此结构,然后再为要var指向的字符串创建malloc()空间,则需要free()该字符串以及free()构造该结构.

As such, if you make this struct and then malloc() space for the string you want var to point to, you need to free() the string as well as free()ing the struct.

一些代码演示了如何工作:

Some code demonstrating how this might work:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

typedef struct {
    char *var;
} EXAMPLE;

int main(int argc, char *argv[]) {

    // malloc() space for the EXAMPLE struct.
    EXAMPLE *point = malloc(sizeof(EXAMPLE));
    // malloc() space for the string that var points to.
    point->var = malloc(20 * sizeof(char));
    // Copy "Hello!" into this memory (care with strcpy).
    strcpy(point->var, "Hello!");
    // Print it, it works!
    printf("point->var is: %s\n", point->var);

    // Free stuff.
    free(point->var);
    free(point);

    return 0;
}

还请注意,我们不强制转换malloc()的结果,在C语言中,您并非要这么做.还要注意,我们在点之前先free() point-> var.这很重要,因为如果首先free()指向,则会丢失指向point-> var的指针,并且会发生内存泄漏.

Also note that we don't cast the result of malloc(), in C you're not meant to. Also note that we free() point->var first before point. This is important because if we free() point first, we lose the pointer to point->var, and we have a memory leak.

这篇关于释放结构指针还会释放C中分配给结构内部的内存吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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