是否有 C 编译器标志来检查函数修改的输入参数?

Is there a C compiler flag to check function modified input parameter?

我想知道,是否有 C 编译器(即 GCC 或 GHS)检查输入参数是否被修改的标志?

我的意思是,如果我有以下函数,如果我不添加 constxy 可能会在函数内被修改(就像现在发生的那样)给他们。所以我想知道编译器是否可以检测到这种情况以及是否存在这样做的标志。

int16_t myFunc(int16_t* x ,int16_t* y, bool* e) 
{   
     int16_t z = 0;

     z = *x + *y;
     *x = 16; // this is wrong on purpose and I would like to detect it
      
     if ( z < 0)
     {
         *e = true;
     }

    return z;
}

您唯一要做的就是像这样使用 const

int16_t myFunc(const int16_t* x ,int16_t* y, bool* e)
{
   ...
   *x = 42;  // compiler error here
   ...
}

此处编译器将发出诊断,例如 assignment of read-only location '*x'

这就是 const 关键字的用途,这就是您要查找的“标志”。

您应该尽可能将 const 放在指针参数上。如果您知道参数指向的对象不会被修改,请使用 const.

I was wondering, is there a flag for the C compiler to check whether an input parameters is modified or not?

有很多C编译器。我听说 GCC, Clang, TinyCC, nwcc...(在 Linux 上;他们中的大多数是开源的,您可以下载他们的源代码并对其进行改进)。你也可以自己写一个。

函数 myFunc 可以将某些 int16_t tab[12]; 的地址传递给另一个被调用的函数 myOtherFunc,该函数有条件地调用第三个函数 myBizarreFunc,后者将修改 tab[3]

很多C代码都有function pointers. That function pointer could be computed -in practice- at runtime (e.g. on Linux with dlopen(3) and dlsym(3), or using libgccjit...),后来用于一些间接调用。

如果您使用最近的 GCC(2021 年,GCC 10 at least), you could write your own GCC plugin to do the static analysis you want (on GIMPLE representations, perhaps also using the Ghudi library). You could base your development on the Bismon static source code analyzer (then contact me by email to basile.starynkevitch@cea.fr). See also (in 2021) this DRAFT 报告。

如果你使用 GCC,你可以编译 和 linkgcc -Wall -Wextra -flto -O2 和更多 static analyzer flags 至少像 -fanalyzer .

另请查看 DECODER or CompCert, static analysis tools like Frama-C or the Clang static analyzer or AbsInt

等项目

注意与 Rice's theorem, Gödel's incompleteness theorems, Curry-Howard correspondence, No free lunch theorem, the halting problem 相关的理论限制。

我相信你想做的检查在编译时并不总是可靠的。

您可能会对 abstract interpretation 技巧感兴趣。

您可能会对 address sanitizer or valgrind 等检测工具(修改生成的机器代码)感兴趣,在某些情况下,您可以编写自己的工具(可能作为 C 到 C 代码转换器)。

另请参阅 this and that 个答案