../
// 在C语言中模拟RAII
#import "/template.typ":*

#doc-template(
title: "在C语言中模拟RAII",
date: "2022年3月5日",
body: [

#set heading(numbering: none)

资源安全在C中要比C++中困难不少。C++中有了RAII机制,资源安全可谓得心应手。无怪乎,Stroustrup的《C++程序设计语言》的前半本都在写内存安全和资源安全,而这些也全是用RAII保证的。局部变量一旦出了作用域,其析构函数就被调用了,非常方便。

然而,C语言中就没有这种好用的工具,比如说:

```c
int foo() {
    FILE* fp = fopen("bar", "w");
    if (f == 0) {
        error("failed to open file");
        return -1;
    }
    int ret = do

...

Email: i (at) mistivia (dot) com