当您退出 C 应用程序时,是否会自动释放 malloc 处理的内存? [英] When you exit a C application, is the malloc-ed memory automatically freed?

查看:23
本文介绍了当您退出 C 应用程序时,是否会自动释放 malloc 处理的内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下 C 代码:

Let's say I have the following C code:

int main () {
  int *p = malloc(10 * sizeof *p);
  *p = 42;
  return 0;  //Exiting without freeing the allocated memory
}

当我编译并执行那个C程序时,即在内存中分配了一些空间后,我分配的内存在我退出应用程序并且进程终止后还会被分配(即基本上占用空间)吗?

When I compile and execute that C program, ie after allocating some space in memory, will that memory I allocated be still allocated (ie basically taking up space) after I exit the application and the process terminates?

推荐答案

这取决于操作系统.大多数现代(和所有主要)操作系统都会释放程序结束时未释放的内存.

It depends on the operating system. The majority of modern (and all major) operating systems will free memory not freed by the program when it ends.

依赖这个是不好的做法,最好明确地释放它.问题不仅仅是您的代码看起来很糟糕.您可能决定将您的小程序集成到一个更大的、长时间运行的程序中.然后一段时间后,您必须花费数小时来跟踪内存泄漏.
依赖操作系统的功能也会降低代码的可移植性.

Relying on this is bad practice and it is better to free it explicitly. The issue isn't just that your code looks bad. You may decide you want to integrate your small program into a larger, long running one. Then a while later you have to spend hours tracking down memory leaks.
Relying on a feature of an operating system also makes the code less portable.

这篇关于当您退出 C 应用程序时,是否会自动释放 malloc 处理的内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆