简体   繁体   中英

valgrind (memcheck) tool didnot detect memory-leak

I introduced memory errors with following piece of C code:

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char** argv){
int i;
int *a = (int *)malloc(sizeof(int) * 10);
if (!a) return -1; /*malloc failed*/
for (i = 0; i < 11; i++){
  a[i] = i;
}

for (i = 0; i < 11; i++){
printf("a[%d] = %d\n",i ,a[i] );
}
// free(a);
return 0;
}

memcheck detects the errors Invalid read/write and definitely lost, which is correct and expected.

Now, I added the same piece of code to a shared object file(.so) of my application. This application runs as a service and is a daemon process. It never exits. I applied valgrind to my application and invoked the modified '.so' .

Memcheck detects Invalid read/write errors, but not definitely lost though all these errors are in one method.can i get some help in making memcheck detect memory leak (definitely lost) error?

Thanks in advance, PV

How can valgrind know that you lost track of your allocated memory? It could see at the program end that the memory is not deallocated, but this is everything it can do for you. And if the program never exits, valgrind thinks you might still want to deallocate it later.

Even if valgrind would inspect all the variables and try to detect that no one points to the beginning of your allocated memory: it's perfectly legitimate to store the address in some modified form; for example, to the byte past the real beginning (think Pascal strings). So valgrind cannot detect if your code still knows about the allocated memory. Thus valgrind couldn't help you even this way.

To actually make valgrind detect the leak, you have to affect another value to a .

Try adding :

a = NULL;

after your for() loop.

Now valgrind should complain!
It won't tell you that you "irremediably lost" your memory unless you lose track of it.

I think that you mean

for (i = 0; i < 10; i++)

It would be preferable however to put a

#define N 10

or

const int N = 10;

at the beginning of your code, then to use the symbol N rather than the 10 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM