简体   繁体   English

C - 在 SIGINT 上免费分配 memory

[英]C - Free allocated memory on SIGINT

I want to write a program which will fill the computer's memory with 0's until malloc() fails.我想编写一个程序,它将用 0 填充计算机的 memory 直到malloc()失败。 However, I wasn't sure if killing the program with Ctrl + C would free this memory.但是,我不确定使用Ctrl + C杀死程序是否会释放这个 memory。 I added some signal-handling code, so that when the program receives SIGINT , the allocated memory is freed and the program is killed.我添加了一些信号处理代码,这样当程序接收到SIGINT时,分配的 memory 被释放并且程序被杀死。

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.我的代码似乎有效,但我想知道这种在SIGINT上释放 memory 的方法是否有意义,或者是否有更好的方法。

My code:我的代码:

#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.但是,我不确定用 Ctrl+C 杀死程序是否会释放这个 memory。

On any modern OS, it will.在任何现代操作系统上,它都会。

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.我的代码似乎有效,但我想知道这种在 SIGINT 上释放 memory 的方法是否有意义,或者是否有更好的方法。

Your code is deeply flawed (in addition to being pointless).您的代码存在严重缺陷(除了毫无意义之外)。

malloc and free are not async-signal safe. mallocfree不是异步信号安全的。 Calling them from a signal handler invokes undefined behavior, and your program may crash at random times.从信号处理程序调用它们会调用未定义的行为,并且您的程序可能会随机崩溃。

Finally, your inthandler() is never actually called -- you need to call signal() or sigaction() to actually set the inthandler as a SIGINT handler.最后,您的inthandler()永远不会被实际调用——您需要调用signal()sigaction()才能将inthandler实际设置为SIGINT处理程序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM