Valgrind not detecting memory leak in threaded c++ program in raspberry pi

114 Views Asked by At
#include <iostream>
#include <thread>
#include <stdlib.h>
void *liveDataPush(void *);
using namespace std;
int main(void)
{
    pthread_t liveDataPushThread;
    int  RetThrd;
    void *ptr;
    RetThrd=pthread_create(&liveDataPushThread,NULL,liveDataPush, ptr);
    if (RetThrd != 0)
    {
        cout << "RetThrd" << endl;
    }
    for (int i = 0; i < 10000; i++)
    {
        int *j = (int *)(malloc(1024 * sizeof(int)));
        cout << "Hi" << endl;
        //free(j);
    }
    pthread_join(liveDataPushThread, NULL);
    return 0;
}
void *liveDataPush(void *)
{
    int *i = new int;
    *i = 30;
    //delete i;
    for (int i = 0; i < 10000; i++)
    {
        int *j = new int[1024];
        cout << "Hello" << endl;
        //delete[] j;
    }
    return NULL;
}

I have stored this program in raspberry pi board and trying to generate memory leak errors using valgring in putty terminal. I tried :

gcc  -Wall -pedantic -g valgrind.cpp -o vlgrnd -pthread -lstdc++ 
valgrind --leak-check=yes ./vlgrnd
valgrind --tool=memcheck --leak-check=yes --show-reachable=yes --num-callers=20 --track-fds=yes ./vlgrnd
valgrind --tool=memcheck --vgdb=yes --vgdb-error=0 --leak-check=full ./vlgrnd

with (in another putty terminal)

gdb ./vlgrnd
target remote | vgdb

monitor leak_check full reachable any

None of them are detecting memory leak.

Using pthread_t along with #include thread, pthread_create, -pthread(during gcc compile) is causing "valgrind --leak-check=yes ./vlgrnd" not to return HEAP, LEAK and ERROR SUMMARIES.valgrind output without SUMMARIES If we remove(comment out) thread related keywords and call thread as normal function and compile without pthread, then valgrind commands return SUMMARIES. valgrind output with SUMMARIES My question is what is the valgrind command that producet memory leak errors for this program

1

There are 1 best solutions below

2
Daniel Langr On

The allocations written in your program are not part of its observable behavior. The compiler is then free to optimize them away. Here is a live demo, where neither malloc nor operator new is ever called in the generated machine code:

https://godbolt.org/z/oG788ebTx