read_age.c¶
Compile with: gcc -g -Wall -std=c11 -o read_age read_age.c
#include <stdio.h>
#include <stdlib.h>
int main() {
int age;
printf("What is your age? ");
scanf("%d", &age);
printf("You are %d years old\n", age);
}
corrupt_mem.c¶
#include <stdlib.h>
int main(int argc, char** argv) {
int a[2];
int* b = malloc(2*sizeof(int));
int* c;
a[2] = 5;
b[0] += 2;
c = b+3;
free(&(a[0]));
free(b);
free(b);
b[0] = 5;
return EXIT_SUCCESS;
}
leaky.c¶
Compile with: gcc -g -Wall -std=c11 -o leaky leaky.c
Use valgrind to check:
valgrind ./leaky
valgrind --leak-check=full ./leaky
#include <stdio.h>
#include <stdlib.h>
#define LEN 5
int main() {
int* ptr1 = malloc(LEN * sizeof(int));
int* ptr2 = calloc(LEN, sizeof(int));
printf("%d\n", ptr1[0]); // Undefined behavior!
printf("%d\n", ptr2[0]); // OK, initialized to 0 by calloc
free(ptr1);
}