简体   繁体   English

如何通过静态分析检测巨大C代码中的内存泄漏(不使用任何工具)

[英]How to detect memory leak in huge C code by static analysis(without using any tool)

How to detect memory leak in third party C code by static analysis(without using any tool). 如何通过静态分析(不使用任何工具)检测第三方C代码中的内存泄漏。 Like how do we verify that the allocated memory has been freed without using any tools? 就像我们如何验证未使用任何工具释放分配的内存?

If you're not going to be using any tool, then of course all you can do is read the code, and think about how it executes. 如果您不打算使用任何工具,那么您所能做的就是阅读代码,并考虑其执行方式。

  • Are there any corner cases where the exucution splits into rarely-taken paths, that might fail to free resources? 是否有极端情况下执行被分割成很少采用的路径,这可能无法释放资源?
  • How about the I/O, can that fail and cause unexpected paths to be taken? I / O会失败并导致采用意外路径吗?

Not using any tools for this is a very strange restriction, of course. 当然,不使用任何工具是一个非常奇怪的限制。

Talking in absolute terms, "you can't". 用绝对的话说,“你不能”。

How can you spot a leak in this code (it has no sense, it's only to make you understand). 如何在此代码中发现泄漏(没有意义,仅是为了使您理解)。 If the users pass 1 as the command line parameters, the code will not leak. 如果用户通过1作为命令行参数,则代码不会泄漏。 However, if he pass 2... 但是,如果他通过2 ...

int main(int argc, const char * argv[]) {
    //insert code here...

    int numberOfLoops = atoi(argv[1]);

    int i = 0;
    void *ptr;
    for (i = 0; i <= numberOfLoops; i++) {
        ptr = malloc(sizeof(int));
        printf("loop\n");
    }

    free(ptr);

    return 0;
}

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

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