gpt4 book ai didi

c - 如果我们不使用 free() 来分配内存会发生什么

转载 作者:行者123 更新时间:2023-11-30 14:39:22 25 4
gpt4 key购买 nike

如果我使用malloc()分配内存并且不使用 free()取消分配内存。为什么其他程序不能通过覆盖以前的内容来访问该内存

void main()
{
int *a; //here a is holding a junk value

MALLOC(a,1,int);
*a=100; //a is holding 100

MALLOC(a,1,int);
*a=200; //a is holding 200

/* so memory location where the value 100 is stored is inaccessible
cannot be reused */
//why can't we just over write that memory space when used next time
}

最佳答案

您正在使用一个非常奇怪的宏,标准 C 中的分配将如下所示:

int * const a = malloc(sizeof *a);
if (a != NULL)
{
*a = 100;
}

然后第二次分配完成,无需调用free(),并覆盖a的内容;这是非常糟糕的,因为它会泄漏内存。这就是为什么我在上面将其声明为 * const ,以表明典型使用中的指针变量不应被覆盖,因为我们希望保留其值。

当程序结束时,在典型的现代系统上,该进程使用的所有资源将由操作系统回收,并且内存将用于其他用途。

调用free()的需要主要是关于程序运行时完成的分配,如果分配重复发生,进程就会不断增长,否则就会增长。 p>

关于c - 如果我们不使用 free() 来分配内存会发生什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56109006/

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