gpt4 book ai didi

c - 如何清理C中分配的内存?

转载 作者:行者123 更新时间:2023-12-04 09:36:57 28 4
gpt4 key购买 nike

我编写了以下玩具程序并观察到第二个变量 测试 2 将取第一个变量释放的内存地址测试 1 .即使我释放(test1),test2 也会保留 test1 的字段值。我想知道如何清理C中free()留下的数据:

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

typedef struct test_str
{
char name[128];
int Id;
} test_str;

typedef test_str* mytest;

int main()
{

mytest test1 = malloc(sizeof(test_str));
printf("test1 pointer address is %p \n", test1);
strcpy(test1->name, "hello world");
test1->Id = 10;

free(test1);
// test1->name = NULL; /* this does not work */
// test1->Id = 0; /* without resetting Id = 0, test2->Id will show 10 */
test1 = NULL;

mytest test2 = malloc(sizeof(test_str));
printf("test2 pointer address is %p, name field is %s, Id = %d \n", test2, test2->name, test2->Id);

return 0;
}

这是输出:

test1 pointer address is 0x2401010
test2 pointer address is 0x2401010, name field is hello world, Id = 10

最佳答案

如果您的数据如此敏感,请使用平台调用来固定内存并使用不可省略的调用来访问某些 memset - 在免费之前清除的变体。

当您将内存返回给运行时,它可以自由地用于下一个拟合请求。是否以及何时这样做,或者是否将内存返还给可能的操作系统,都不是标准规定的。

旁白:void free(void*) {}free 的有效实现.

关于c - 如何清理C中分配的内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23281331/

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