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

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

问题描述

例如我有这个结构:

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
", point->var);

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

    return 0;
}

另请注意,我们不会强制转换 malloc() 的结果,在 C 中您不应该这样做.还要注意我们 free() point->var 在 point 之前.这很重要,因为如果我们 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天全站免登陆