Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
176 views
in Technique[技术] by (71.8m points)

c - Why does valgrind not show the obvious leaks in my program?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

After all those comments, the answer is kind of silly...

Your screenshot shows you ran valgrind ./substitution, without passing any command line arguments to your program. When this happens it prints Usage: ./substitution key and exits without doing anything further; in particular without calling cipher() and thus without ever calling malloc(). So of course there is no memory leak in this case.

If you run the program with a key argument on the command line, and give it some input, you should see valgrind report the memory leak:

==15815== 
==15815== HEAP SUMMARY:
==15815==     in use at exit: 54 bytes in 2 blocks
==15815==   total heap usage: 4 allocs, 2 frees, 2,102 bytes allocated
==15815== 
==15815== LEAK SUMMARY:
==15815==    definitely lost: 54 bytes in 2 blocks
==15815==    indirectly lost: 0 bytes in 0 blocks
==15815==      possibly lost: 0 bytes in 0 blocks
==15815==    still reachable: 0 bytes in 0 blocks
==15815==         suppressed: 0 bytes in 0 blocks
==15815== Rerun with --leak-check=full to see details of leaked memory

Although in principle a compiler could optimize out the malloc calls, in my tests with gcc and clang with -O3, I couldn't find any indication of them actually doing so.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...