find memory leak with Valgrind
Valgrind
Install in Ubuntu:
sudo apt-get install valgrind
Test code, check_leak_demo.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct leak_example {
char *ptr;
};
void leak1(void){
int *ptr = (int *)malloc(100);
if (!ptr) {
printf("Oops, malloc fail!\n");
}
}
char *leak2(void){
char *ptr = strdup("Hey Hey Hey!\n");
if (!ptr) {
printf("Oops, strdup fail!\n");
return 0;
}
return ptr;
}
struct leak_example *leak3(void){
struct leak_example *ptr = 0;
ptr = (struct leak_example *) malloc(sizeof(struct leak_example));
if (!ptr) {
printf("Oops, malloc fail!\n");
}
ptr->ptr = strdup("Hey Hey Hey!\n");
return ptr;
}
int main(){
struct leak_example *lk_ptr;
char * ch_ptr = 0;
leak1();
ch_ptr = leak2();
if(ch_ptr) {
printf("%s", ch_ptr);
}
lk_ptr = leak3();
if(lk_ptr) {
printf("%s", lk_ptr->ptr);
free(lk_ptr);
}
return 0;
}
Build command
$ gcc -g -o check_leak_demo check_leak_demo.c
Execute Valgrind
$ valgrind --leak-check=full --show-leak-kinds=all --verbose ./check_leak_demo
Test result:
// there are 3 leaks
How to modify leak ?
check my comments “//solve leak“.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct leak_example {
char *ptr;
};
void leak1(void){
int *ptr = (int *)malloc(100);
if (!ptr) {
printf("Oops, malloc fail!\n");
}
free(ptr); //solve leak
}
char *leak2(void){
/* //method 2
char test[20];
sprintf( test, "Hey Hey Hey!\n");
return strdup(test);
*/
char *test = "Hey Hey Hey!\n";
char *ptr = strdup(test);
if (!ptr) {
printf("Oops, strdup fail!\n");
return 0;
}
return ptr;
}
struct leak_example *leak3(void){
struct leak_example *l_ptr = 0;
l_ptr = (struct leak_example *) malloc(sizeof(struct leak_example));
if (!l_ptr) {
printf("Oops, malloc fail!\n");
}
l_ptr->ptr = strdup("Hey Hey Hey!\n");
return l_ptr;
}
int main(){
struct leak_example *lk_ptr;
char * ch_ptr = 0;
leak1();
ch_ptr = leak2();
if(ch_ptr) {
printf("%s", ch_ptr);
free(ch_ptr);//solve leak
}
lk_ptr = leak3();
if(lk_ptr) {
printf("%s", lk_ptr->ptr);
free(lk_ptr->ptr);//solve leak
free(lk_ptr);
}
return 0;
}
Last modified 11mo ago