【问题标题】:Does GCC have features to detect use-after-free bugs? [duplicate]GCC 是否具有检测 use-after-free 错误的功能? [复制]
【发布时间】:2021-11-25 04:10:21
【问题描述】:

这是我的代码 sn-p:

#include <stdlib.h>
#include <stdio.h>

typedef struct node
{
    char key;          // value
    struct node *next; // pointer to the next element
} Node;

int main(void)
{
    Node *n = malloc(sizeof(Node));
    n->key = 'K';
    n->next = NULL;

    free(n);

    printf("%c\n", n->key);
}

当上面的sn-p编译运行时...

ganningxu@Gannings-Computer:~/test$ gcc test_faults.c -o test_faults; ./test_faults
K

ganningxu@Gannings-Computer:~/test$ clang test_faults.c -o test_faults; ./test_faults
K

访问释放的内存时没有编译器警告或错误。有没有办法强制编译器显示此类错误?

【问题讨论】:

  • 没有。使用像valgrind 这样的调试工具。
  • 编译器一般不关心内存管理。它的工作是将 C 代码翻译成机器代码
  • @EugeneSh。我认为他的意思是强制它生成产生错误的代码。
  • 一种常用的解决方法是在free之后将指针设置为NULL ... free(x); x = NULL;

标签: c gcc clang


【解决方案1】:

使用GCC编译时,可以使用-fsanitize=address so that “Memory access instructions are instrumented to detect out-of-bounds and use-after-free bugs.”,这当然会影响程序性能,如果有bug也可能会改变程序的行为。

【讨论】:

    猜你喜欢
    • 2017-11-08
    • 1970-01-01
    • 2020-07-23
    • 1970-01-01
    • 2022-11-21
    • 1970-01-01
    • 2012-08-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多