C - 在 SIGINT 上释放分配的内存

C - Free allocated memory on SIGINT

我想编写一个程序,用 0 填充计算机的内存,直到 malloc() 失败。但是,我不确定用 Ctrl+C 终止程序是否会释放这个内存。我添加了一些信号处理代码,以便当程序接收到 SIGINT 时,分配的内存被释放并且程序被终止。

我的代码似乎可以工作,但我想知道这种在 SIGINT 上释放内存的方法是否有意义,或者是否有更好的方法。

我的代码:

#include <stdlib.h>
#include <signal.h>

int *ptr;

void inthandler(int dummy) { /* what does this argument do? */
   extern int *ptr;
   free(ptr);
   exit(-1);
}

int main(void) {
   signal(SIGINT, inthandler);
   extern int *ptr;
   while ((ptr = malloc(sizeof *ptr)) != NULL) {
         *ptr = 0;
   }
}

However, I wasn't sure if killing the program with Ctrl+C would free this memory.

在任何现代 OS 上,它都会。

My code appears to work, but I want to know if this method of freeing memory on SIGINT makes sense, or if there is a better way to do it.

您的代码存在严重缺陷(除了毫无意义之外)。

mallocfree 不是异步信号安全的。从信号处理程序调用它们会调用未定义的行为,您的程序可能会随机崩溃。

最后,您的 inthandler() 从未真正被调用——您需要调用 signal()sigaction() 才能将 inthandler 实际设置为 SIGINT处理程序。

更新:

I added the signal() call to the program.

正如我所说,这使程序 变得更糟(因为在信号处理程序中调用 free() 是不安全的)。

if killing the program frees its memory, why is it necessary to call free() on allocated memory after the program is done using it?

正如 Chris Dodd 评论的那样,永远不需要 free 程序中即将退出的内存 -- OS 会自动执行此操作。

只需要 free() 内存 IFF 程序将保留 运行ning 并且 将来会分配更多内存。在那种情况下,如果程序没有free()它之前分配的内存,它将最终运行超出堆。