Skip to content

Instantly share code, notes, and snippets.

@carlos-jenkins
Created February 7, 2014 23:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save carlos-jenkins/8873932 to your computer and use it in GitHub Desktop.
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.
#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