valgrind output

I am running the following code with valgrind to detect memory leak:

valgrind --tool=memcheck --leak-check=full --trace-children=yes --show-reachable=yes -- --log-file=val.log ./valgrind.out

If I do "tail -f val.log" it doesn't have any information until I kill the script.

I thought while the program is running, I should be able to see the leaks.  
int main()
  char *p;

  while (1) {
     // Allocation #1 of 19 bytes
     p = (char *) malloc(19);

    // Allocation #2 of 12 bytes
     p = (char *) malloc(12);

     // Allocation #3 of 16 bytes
     p = (char *) malloc(16);

    sleep (6);

  return 0;

Open in new window

Who is Participating?
evilrixConnect With a Mentor Senior Software Engineer (Avast)Commented:
From the valgrind manual:

"Memcheck keeps track of all heap blocks issued in response to calls to malloc/new et al. So when the program exits, it knows which blocks have not been freed."

In other words, you will have to signal your daemon to terminate gracefully so that valgrind can report. One way to do this would be to trap signals and have your process spawn a child of itself and then for it to terminate. This way, your service would continue running (all be it a new process instance). You could then send (for example) a SIGHUP to your service to signal it to spawn a new instance of itself and then terminate at times you feel appropriate.
evilrixSenior Software Engineer (Avast)Commented:
>> I thought while the program is running, I should be able to see the leaks.  
Until the program has finished it has no idea if there are leaks. Only at that point is it able to say with impunity that there has been memory leakage.
learningunixAuthor Commented:
ohh...than how can I run valgrind to detect memory leaks against my c++ application which is running in the background as a daemon
evilrixSenior Software Engineer (Avast)Commented:
Another option is to use a static analysis program to check the integrity of your code. Some of these are pretty good and spot potential memory leaks. I say potential, because they don't always get it right but at least, if you investigate and rule it out that's better than having no idea.

Also, prevention is better than cure. Rather than using malloc and free you should consider new/delete (since you are using C++ these are absolutely what you should be using). You can then take advantage of smart pointers to avoid leaks altogether.

"C++ Smart pointers"

learningunixAuthor Commented:
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.