-
-
Save carlos-jenkins/8873932 to your computer and use it in GitHub Desktop.
Valgrind test program to demostrate memory access violation, memory leak or double free problems in a C program.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdlib.h> | |
#include <stdio.h> | |
// Compile with: | |
// gcc -std=c99 -g -Wall -O0 -o vg vg.c | |
// Run with: | |
// valgrind --leak-check=full ./vg [1|2|3] | |
int read_and_write(int* buff, int size, int seed) | |
{ | |
// Write something | |
for(int i = 0; i < size; i++, seed++) { | |
buff[i] = seed; | |
} | |
// Read something | |
int result = 0; | |
for(int i = 0; i < size; i++) { | |
result += buff[i]; | |
} | |
return result; | |
} | |
int main(int argc, char* argv[]) | |
{ | |
if (argc != 2) { | |
printf("Usage: ./vg [1|2|3]\n"); | |
return 1; | |
} | |
int error = atoi(argv[1]); | |
int buff_size = 10; | |
int* buff = NULL; | |
// ERR1 : Memory access violation (read and write) | |
if (error == 1) { | |
buff = (int*) malloc(sizeof(int) * buff_size); | |
printf( | |
"First error, go beyond memory boundaries {%d}\n", | |
read_and_write(buff, buff_size + 10, rand()) | |
); | |
free(buff); | |
return 1; | |
} | |
// ERR2 : Memory leak | |
if (error == 2) { | |
buff = (int*) malloc(sizeof(int) * buff_size); | |
printf( | |
"Second error, forget to free memory {%d}\n", | |
read_and_write(buff, buff_size, rand()) | |
); | |
return 1; | |
} | |
// ERR3 : Double free | |
if (error == 3) { | |
buff = (int*) malloc(sizeof(int) * buff_size); | |
printf( | |
"Third error, free memory twice {%d}\n", | |
read_and_write(buff, buff_size, rand()) | |
); | |
free(buff); | |
free(buff); | |
return 1; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment