GCC 是否具有检测释放后使用错误的功能?

Gan*_* Xu 4 c gcc clang

这是我的代码片段:

#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);
}
Run Code Online (Sandbox Code Playgroud)

当上面的代码片段被编译并运行时......

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
Run Code Online (Sandbox Code Playgroud)

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

Eri*_*hil 8

使用 GCC 编译时,可以使用-fsanitize=address\xe2\x80\x9c 内存访问指令来检测越界和释放后使用错误。\xe2\x80\x9d这当然会影响程序性能,并且如果存在错误,它也可能会改变程序行为。

\n


归档时间:

查看次数:

1024 次

最近记录:

4 年,11 月 前