【发布时间】: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;