Those of you who haven't heard about ValGrind : It is Gates of Death or gates of Valhalla in Norse Mythology.
I just love mythology. I am not sure, how true it is , but for the time humans were born it existed.
It is our fear , our love , our redemption.
Its changes as humans changes, it is ever evolving.
But this post is not about Gates of Valhalla. ( Does Max max : Fury Road) rings a bell
This post is about second ValGrind : Which is debugging tool suite, It has one tool called MEMCHECK, which helps in checking if your C or C++ program is leaking memory.
Now in the older post, we have seen how to debug crash and know why your program crashed. But seriously, we will not always wait for our program to crash. So we use Memcheck to see if our program gotta piss or not.
1) If you want to use something, you need to have it. So install it first on your linux machine. Pretty easy. Simply run
> sudo apt-get install valgrind.
2) I will take the example, where my .C file is crash.c and my program is crash. To run on this you have to give below command.
> valgrind --tool=memcheck --leak-check=full ./crash
Now what happens is that the output of this command will come on your terminal and which is not easy to read.
So better put that into some file say "val.txt".
> valgrind --tool=memcheeck --leak-check=full -log-file="val.txt" ./crash
now for my below code, the valgrind output was
Crash.c file
#include<stdio.h>
#include<stdlib.h>
void voldemort(int *);
int main()
{
int *hp;
hp=(int *)malloc(sizeof(int)*1);
voldemort(hp);
// free(hp);
}
void voldemort(int *hp)
{
int *temp;
temp = hp;
*temp=2;
hp=NULL;
*hp=10;
}
Valgrind output
==8949== Memcheck, a memory error detector
==8949== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==8949== Using Valgrind-3.10.0.SVN and LibVEX; rerun with -h for copyright info
==8949== Command: ./crash
==8949== Parent PID: 5602
==8949==
==8949== Invalid write of size 4
==8949== at 0x8048463: voldemort (crash.c:20)
==8949== by 0x8048441: main (crash.c:10)
==8949== Address 0x0 is not stack'd, malloc'd or (recently) free'd
==8949==
==8949==
==8949== Process terminating with default action of signal 11 (SIGSEGV): dumping core
So if you see , it is telling that at line 20 , there is invalid write. which if we see in crash.c file is correct, and we can modify our program to handle it.
So thats it ...
PLUG the LEAK
No comments:
Post a Comment