Here is my code snippet:
#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);
}
When the above snippet is compiled and run...
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
There are no compiler warnings or errors when the freed memory is accessed. Is there any way to force the compiler to show such errors?
CodePudding user response:
When compiling with GCC, you can use -fsanitize=address
so that “Memory access instructions are instrumented to detect out-of-bounds and use-after-free bugs.” This will of course affect program performance, and it may also change the program behavior if there are bugs.