gpt4 book ai didi

无法从结构成员变量中释放内存

转载 作者:太空宇宙 更新时间:2023-11-04 05:33:58 27 4
gpt4 key购买 nike

<分区>

我在 C 中对结构变量调用 free 后,检查该变量是否为 NULL,它告诉我它不是 NULL。所以 free 没有用?我的代码:

struct main_struct {
struct my_file *file;
};

struct my_file {
char *host;
int port; // this cannot be malloc'ed and free'ed
};

struct my_file* read_file() {
FILE *f;
struct my_file *file;

//open FILE for reading..

file = malloc(sizeof(struct my_file)); //allocate memory for my_file struct
memset(file, 0, sizeof(struct my_file));

// while loop to read file content..
// in the loop:
char *value = line;
file->host = malloc(sizeof(char) * strlen(value)); //allocate memory for host member variable
strncpy(file->host, value, strlen(value)); //assign value to host variable

return file;
}

int main() {
struct main_struct *mstr;
mstr = malloc(sizeof(struct main_struct)); //allocate memory to main_struct
memset(mstr, 0, sizeof(struct main_struct));

mstr->my_file = read_file(); //call to read file, allocate mem for my_file struct and the 'host' member variable

// some code

// call free here:
if(mstr->my_file->host != NULL) {
free(mstr->my_file->host);
}
// check if mem has been freed:
if(mstr->my_file->host == NULL) {
printf("mstr->my_file->host is NULL, good.\n");
} else {
printf("mstr->my_file->host is NOT NULL, bad.\n"); // I see this.
}

// I also try to free mstr->my_file:
if(mstr->my_file != NULL) {
free(mstr->my_file);
}
// check if mem has been freed:
if(mstr->my_file == NULL) {
printf("mstr->my_file is NULL, good.\n");
} else {
printf("mstr->my_file is NOT NULL, bad.\n"); // I see this.
}

// and also mstr itself..
}

我是否正确使用了 free 函数,因为我看到过这样调用 free 的示例:free(&mystruct->myfile->host); 通过发送指向 free 的指针地址。但我认为我现在调用免费电话的方式是正确的..?

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com