gpt4 book ai didi

C 清理错误/终止

转载 作者:行者123 更新时间:2023-12-02 06:58:04 28 4
gpt4 key购买 nike

我按顺序运行了一堆malloc,并且每次都检查以确保它是成功的。像这样:

typedef struct {
int *aray;
char *string;
} mystruct;

mystruct *mystruct_init(int length)
{
mystruct *foo = malloc(sizeof(int *));
if (!foo) exit(1);

foo->array = malloc(length * sizeof(int));
if (!foo->array) exit(1);

foo->string = malloc(length * sizeof(char));
if (!foo->string) exit(1);

return foo;
}

因此,当 malloc 失败时,程序会退出而不释放之前的那些。有哪些技术可以确保在出现故障时程序安全退出并释放所有分配的内存?

最佳答案

大多数现代操作系统会在调用 exit(...) 后进程终止后释放正确的内存。这些操作系统包括:

  • 所有 Unix 变体,包括 Linux 和 Mac OS X
  • 所有 Windows 版本
  • 所有 DOS 变体

关于C 清理错误/终止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27051107/

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