SlideShare une entreprise Scribd logo
1  sur  29
Télécharger pour lire hors ligne
Detecting Memory Leaks
with Valgrind
by Rigels Gordani
Rigels Gordani
Computer Engineer
Intecs S.p.A
Automotive Unit
- In Vehicle Infotainment,
- Linux Embedded,
- AUTOSAR
Products Unit
- Porting Linux
applications to Windows
About me
Collaborated with
Detecting Memory Leaks with Valgrind
Memory errors lead to faults like segmentation faults,
which are very common while dealing with pointers
in C/C++ programming.
Identifying and fixing compilation errors is quite easy,
but the task of fixing segmentation faults and
memory leaks is very tedious.
Detecting Memory Leaks with Valgrind
Valgrind is a memory checker, it is designed to be as
non-intrusive as possible.
It works directly with existing executables.
You don’t need to recompile, relink,
or otherwise modify the program to be checked.
Detecting Memory Leaks with Valgrind
Latest stable version as speaking of Valgrind is 3.8.x.
The following platforms support Valgrind:
- x86 and x86_64 Linux
- ARM Linux and ARM Android ( >= 2.3.x)
- PPC32 and PPC64 Linux
- S390X Linux
- MIPS Linux
- x86 Android (>= 4.0)
- x86 and AMD64 Darwin
Detecting Memory Leaks with Valgrind
In this presentation we will explore how to use Valgrind
to detect memory errors in a program written in C/C++
using MemCheck tool.
Apart from MemCheck tool, Valgrind also includes:
- thread error detectors,
- a cache and branch-prediction profiler,
- a call-graph generating cache
- and branch-prediction profiler,
- a heap profiler and other experimental tools.
Detecting Memory Leaks with Valgrind
What kind of problems can be detected with Valgrind 's
memcheck:
1. Not releasing acquired memory using delete/free.
2. Writing into an array with an index that's out of bounds
3. Trying to reference/dereference a pointer that is not yet initialized.
Detecting Memory Leaks with Valgrind
4. Trying to dereference a pointer that is already freed.
5. Passing system call parameters with inadequate buffers for
read/write; i.e., if your program makes a system call passing an
invalid buffer.
6. Uses of undefined variable values.
Detecting Memory Leaks with Valgrind
All the previous situations can give rise to memory
errors, causing the program to terminate abruptly.
This is particularly dangerous in safety and
mission-critical systems, where such abrupt program
termination can have catastrophic consequences.
Hence, it is necessary to detect and resolve such errors
that can lead to segmentation faults.
Detecting Memory Leaks with Valgrind
All the previous situations can give rise to memory
The Valgrind open source tool can be used to detect
some of these errors by dynamically executing the
program.
Memory faults may not cause significant damages in
small programs, but can be extremely dangerous in
safety-critical applications and can have disastrous
consequences; for instance, a segmentation fault in a
medical application may lead to loss of lives.
Detecting Memory Leaks with Valgrind
Let's illustrate the usage of Valgrind through the
following scenarios:
1. Valgrind command line tool.
2. QtCreator integration of Valgrind.
3. Eclipse integration of Valgrind using LinuxTools.
Detecting Memory Leaks with Valgrind
1. Valgrind command line tool.
Compile the C or C++ source file with debugging option:
$ g++ -g example1.cpp -o example1 // for a C++ file
$ gcc -g example1.c -o example1 // for a C file
With -g option, you’ll get messages which point directly
to the relevant source code lines. Omitting -g options,
you'll get only functions name.
Detecting Memory Leaks with Valgrind
1. Valgrind command line tool.
To analyse the program compiled using Valgrind, run
the following command:
$ valgrind --tool=memcheck --leak-check=yes ./example1
Detecting Memory Leaks with Valgrind
1. Valgrind command line tool.
To analyse the program compiled using Valgrind, run
the following command:
$ valgrind --tool=memcheck --leak-check=yes ./example1
Detecting Memory Leaks with Valgrind
1. Valgrind command line tool.
$ gcc -g example1.c -o example1
$ valgrind --tool=memcheck --leak-check=yes ./example1
Out of bounds access, C
compiler doesn't complain
Memory leak
Detecting Memory Leaks with Valgrind
1. Valgrind command line tool.
==6287== Memcheck, a memory error detector
==6287== Copyright (C) 2002-2011, and GNU GPL'd, by Julian Seward et al.
==6287== Using Valgrind-3.7.0 and LibVEX; rerun with -h for copyright info
==6287== Command: ./example1
==6287==
==6287== Invalid write of size 4
==6287== at 0x400567: main (prova.c:14)
==6287== Address 0x51f1068 is 0 bytes after a block of size 40 alloc'd
==6287== at 0x4C2B3F8: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==6287== by 0x400534: main (prova.c:8)
==6287==
==6287==
==6287== HEAP SUMMARY:
==6287== in use at exit: 40 bytes in 1 blocks
==6287== total heap usage: 1 allocs, 0 frees, 40 bytes allocated
==6287==
==6287== 40 bytes in 1 blocks are definitely lost in loss record 1 of 1
==6287== at 0x4C2B3F8: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==6287== by 0x400534: main (prova.c:8)
==6287==
Detecting Memory Leaks with Valgrind
1. Valgrind command line tool.
(continues...)
==6287== LEAK SUMMARY:
==6287== definitely lost: 40 bytes in 1 blocks
==6287== indirectly lost: 0 bytes in 0 blocks
==6287== possibly lost: 0 bytes in 0 blocks
==6287== still reachable: 0 bytes in 0 blocks
==6287== suppressed: 0 bytes in 0 blocks
==6287==
==6287== For counts of detected and suppressed errors, rerun with: -v
==6287== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 2 from 2)
Detecting Memory Leaks with Valgrind
2. QtCreator integration of Valgrind.
Open QtCreator.

Create a C application project.

Edit the C source file

Compile in Debug Mode

Analyze-> Run Valgrind Memory Analyzer
Detecting Memory Leaks with Valgrind
2. QtCreator integration of Valgrind.
Detecting Memory Leaks with Valgrind
2. QtCreator integration of Valgrind.
Advantages of a GUI solution are obvious here:

Very quick problem identification

Click on the error sends to the line of code with the error

No need to run Valgrind from command line, QtCreator does it
Detecting Memory Leaks with Valgrind
3. Eclipse integration of Valgrind
using LinuxTools.
Need to install LinuxTools from Eclipse components.
After installing LinuxTools:

Open Eclipse

Create a new C++ Project.

Edit the C++ file.

Build in Debug Mode

Profile with Valgrind.
Detecting Memory Leaks with Valgrind
3. Eclipse integration of Valgrind
using LinuxTools.
Detecting Memory Leaks with Valgrind
Using C++11 smart pointers like unique_ptr<...>
They allow you to write code that automatically prevents memory or
resource leaks with exception handling.
Smart pointer objects are allocated on the stack and whenever the
smart pointer object is destroyed, it frees the underlying resource.
Detecting Memory Leaks with Valgrind
Using C++11 smart pointers like unique_ptr<...>
Detecting Memory Leaks with Valgrind
Using C++11 smart pointers like unique_ptr<...>
$ valgrind --tool=memcheck --leak-check=full ./example_uniq
==30755== Memcheck, a memory error detector
==30755== Copyright (C) 2002-2012, and GNU GPL'd, by Julian Seward et al.
==30755== Using Valgrind-3.8.1 and LibVEX; rerun with -h for copyright info
==30755== Command: ./example_uniq
==30755==
main()
print()
==30755==
==30755== HEAP SUMMARY:
==30755== in use at exit: 0 bytes in 0 blocks
==30755== total heap usage: 1 allocs, 1 frees, 24 bytes allocated
==30755==
==30755== All heap blocks were freed -- no leaks are possible
==30755==
==30755== For counts of detected and suppressed errors, rerun with: -v
==30755== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 2 from 2)
Detecting Memory Leaks with Valgrind
Valgrind usage in identifying software security problems
Valgrind can identify many of the “Top 25 Most Dangerous Software
Errors” listed in http://cwe.mitre.org/top25/#CWE-676
[4]: Buffer Copy without Checking Size of Input
('Classic Buffer Overflow')
[20]: Incorrect Calculation of Buffer Size
Detecting Memory Leaks with Valgrind
Bibliography:
1. www.valgrind.org
2. GNU Linux Application Programming 2ed, Chapter 34
3. The developers guide to debugging , Spinger ,Holtmann,
Chapter 4, Fixing memory problems
4. Professional C++, Wiley, ISBN 0470932449
5. Valgrind Advanced Debugging and Profiling for GNU/Linux
applications ISBN: 0-9546120-5-1
Detecting Memory Leaks with Valgrind
Thank you
Rigels Gordani rigels_gordani
rigels.gordani

Contenu connexe

Tendances

Network lap pgms 7th semester
Network lap pgms 7th semesterNetwork lap pgms 7th semester
Network lap pgms 7th semester
DOSONKA Group
 

Tendances (20)

[若渴計畫] Challenges and Solutions of Window Remote Shellcode
[若渴計畫] Challenges and Solutions of Window Remote Shellcode[若渴計畫] Challenges and Solutions of Window Remote Shellcode
[若渴計畫] Challenges and Solutions of Window Remote Shellcode
 
semaphore & mutex.pdf
semaphore & mutex.pdfsemaphore & mutex.pdf
semaphore & mutex.pdf
 
Java Performance Analysis on Linux with Flame Graphs
Java Performance Analysis on Linux with Flame GraphsJava Performance Analysis on Linux with Flame Graphs
Java Performance Analysis on Linux with Flame Graphs
 
Page cache in Linux kernel
Page cache in Linux kernelPage cache in Linux kernel
Page cache in Linux kernel
 
Fuzzing: The New Unit Testing
Fuzzing: The New Unit TestingFuzzing: The New Unit Testing
Fuzzing: The New Unit Testing
 
Linux Kernel - Virtual File System
Linux Kernel - Virtual File SystemLinux Kernel - Virtual File System
Linux Kernel - Virtual File System
 
Play with FILE Structure - Yet Another Binary Exploit Technique
Play with FILE Structure - Yet Another Binary Exploit TechniquePlay with FILE Structure - Yet Another Binary Exploit Technique
Play with FILE Structure - Yet Another Binary Exploit Technique
 
AngularJS $http Interceptors (Explanation and Examples)
AngularJS $http Interceptors (Explanation and Examples)AngularJS $http Interceptors (Explanation and Examples)
AngularJS $http Interceptors (Explanation and Examples)
 
eBPF Perf Tools 2019
eBPF Perf Tools 2019eBPF Perf Tools 2019
eBPF Perf Tools 2019
 
twlkh-linux-vsyscall-and-vdso
twlkh-linux-vsyscall-and-vdsotwlkh-linux-vsyscall-and-vdso
twlkh-linux-vsyscall-and-vdso
 
spinlock.pdf
spinlock.pdfspinlock.pdf
spinlock.pdf
 
Linux Profiling at Netflix
Linux Profiling at NetflixLinux Profiling at Netflix
Linux Profiling at Netflix
 
Introduce to Rust-A Powerful System Language
Introduce to Rust-A Powerful System LanguageIntroduce to Rust-A Powerful System Language
Introduce to Rust-A Powerful System Language
 
NTUSTxTDOH - Pwn基礎 2015/12/27
NTUSTxTDOH - Pwn基礎 2015/12/27NTUSTxTDOH - Pwn基礎 2015/12/27
NTUSTxTDOH - Pwn基礎 2015/12/27
 
Heap exploitation
Heap exploitationHeap exploitation
Heap exploitation
 
Network lap pgms 7th semester
Network lap pgms 7th semesterNetwork lap pgms 7th semester
Network lap pgms 7th semester
 
Introduction to Google Guice
Introduction to Google GuiceIntroduction to Google Guice
Introduction to Google Guice
 
Vim Rocks!
Vim Rocks!Vim Rocks!
Vim Rocks!
 
BugBounty Tips.pdf
BugBounty Tips.pdfBugBounty Tips.pdf
BugBounty Tips.pdf
 
Rust vs C++
Rust vs C++Rust vs C++
Rust vs C++
 

En vedette

En vedette (6)

Physics and Marketing
Physics and MarketingPhysics and Marketing
Physics and Marketing
 
10 myths about psychology
10 myths about psychology10 myths about psychology
10 myths about psychology
 
The Future Of Work & The Work Of The Future
The Future Of Work & The Work Of The FutureThe Future Of Work & The Work Of The Future
The Future Of Work & The Work Of The Future
 
Study: The Future of VR, AR and Self-Driving Cars
Study: The Future of VR, AR and Self-Driving CarsStudy: The Future of VR, AR and Self-Driving Cars
Study: The Future of VR, AR and Self-Driving Cars
 
Hype vs. Reality: The AI Explainer
Hype vs. Reality: The AI ExplainerHype vs. Reality: The AI Explainer
Hype vs. Reality: The AI Explainer
 
3 Things Every Sales Team Needs to Be Thinking About in 2017
3 Things Every Sales Team Needs to Be Thinking About in 20173 Things Every Sales Team Needs to Be Thinking About in 2017
3 Things Every Sales Team Needs to Be Thinking About in 2017
 

Similaire à Better Embedded 2013 - Detecting Memory Leaks with Valgrind

Crash dump analysis - experience sharing
Crash dump analysis - experience sharingCrash dump analysis - experience sharing
Crash dump analysis - experience sharing
James Hsieh
 
Joxean Koret - Database Security Paradise [Rooted CON 2011]
Joxean Koret - Database Security Paradise [Rooted CON 2011]Joxean Koret - Database Security Paradise [Rooted CON 2011]
Joxean Koret - Database Security Paradise [Rooted CON 2011]
RootedCON
 
150104 3 methods for-binary_analysis_and_valgrind
150104 3 methods for-binary_analysis_and_valgrind150104 3 methods for-binary_analysis_and_valgrind
150104 3 methods for-binary_analysis_and_valgrind
Raghu Palakodety
 
exploit-writing-tutorial-part-5-how-debugger-modules-plugins-can-speed-up-bas...
exploit-writing-tutorial-part-5-how-debugger-modules-plugins-can-speed-up-bas...exploit-writing-tutorial-part-5-how-debugger-modules-plugins-can-speed-up-bas...
exploit-writing-tutorial-part-5-how-debugger-modules-plugins-can-speed-up-bas...
tutorialsruby
 
exploit-writing-tutorial-part-5-how-debugger-modules-plugins-can-speed-up-bas...
exploit-writing-tutorial-part-5-how-debugger-modules-plugins-can-speed-up-bas...exploit-writing-tutorial-part-5-how-debugger-modules-plugins-can-speed-up-bas...
exploit-writing-tutorial-part-5-how-debugger-modules-plugins-can-speed-up-bas...
tutorialsruby
 
What
WhatWhat
What
anity
 
Analytics tools and Instruments
Analytics tools and InstrumentsAnalytics tools and Instruments
Analytics tools and Instruments
Krunal Soni
 

Similaire à Better Embedded 2013 - Detecting Memory Leaks with Valgrind (20)

How to Perform Memory Leak Test Using Valgrind
How to Perform Memory Leak Test Using ValgrindHow to Perform Memory Leak Test Using Valgrind
How to Perform Memory Leak Test Using Valgrind
 
Valgrind debugger Tutorial
Valgrind debugger TutorialValgrind debugger Tutorial
Valgrind debugger Tutorial
 
150412 38 beamer methods of binary analysis
150412 38 beamer methods of  binary analysis150412 38 beamer methods of  binary analysis
150412 38 beamer methods of binary analysis
 
Davide Berardi - Linux hardening and security measures against Memory corruption
Davide Berardi - Linux hardening and security measures against Memory corruptionDavide Berardi - Linux hardening and security measures against Memory corruption
Davide Berardi - Linux hardening and security measures against Memory corruption
 
Crash dump analysis - experience sharing
Crash dump analysis - experience sharingCrash dump analysis - experience sharing
Crash dump analysis - experience sharing
 
Joxean Koret - Database Security Paradise [Rooted CON 2011]
Joxean Koret - Database Security Paradise [Rooted CON 2011]Joxean Koret - Database Security Paradise [Rooted CON 2011]
Joxean Koret - Database Security Paradise [Rooted CON 2011]
 
150104 3 methods for-binary_analysis_and_valgrind
150104 3 methods for-binary_analysis_and_valgrind150104 3 methods for-binary_analysis_and_valgrind
150104 3 methods for-binary_analysis_and_valgrind
 
Hardwear.io 2018 BLE Security Essentials workshop
Hardwear.io 2018 BLE Security Essentials workshopHardwear.io 2018 BLE Security Essentials workshop
Hardwear.io 2018 BLE Security Essentials workshop
 
Android tools for testers
Android tools for testersAndroid tools for testers
Android tools for testers
 
Audit
AuditAudit
Audit
 
Discussing Errors in Unity3D's Open-Source Components
Discussing Errors in Unity3D's Open-Source ComponentsDiscussing Errors in Unity3D's Open-Source Components
Discussing Errors in Unity3D's Open-Source Components
 
exploit-writing-tutorial-part-5-how-debugger-modules-plugins-can-speed-up-bas...
exploit-writing-tutorial-part-5-how-debugger-modules-plugins-can-speed-up-bas...exploit-writing-tutorial-part-5-how-debugger-modules-plugins-can-speed-up-bas...
exploit-writing-tutorial-part-5-how-debugger-modules-plugins-can-speed-up-bas...
 
exploit-writing-tutorial-part-5-how-debugger-modules-plugins-can-speed-up-bas...
exploit-writing-tutorial-part-5-how-debugger-modules-plugins-can-speed-up-bas...exploit-writing-tutorial-part-5-how-debugger-modules-plugins-can-speed-up-bas...
exploit-writing-tutorial-part-5-how-debugger-modules-plugins-can-speed-up-bas...
 
Valgrind overview: runtime memory checker and a bit more aka использование #v...
Valgrind overview: runtime memory checker and a bit more aka использование #v...Valgrind overview: runtime memory checker and a bit more aka использование #v...
Valgrind overview: runtime memory checker and a bit more aka использование #v...
 
What
WhatWhat
What
 
.Net Debugging Techniques
.Net Debugging Techniques.Net Debugging Techniques
.Net Debugging Techniques
 
.NET Debugging Tips and Techniques
.NET Debugging Tips and Techniques.NET Debugging Tips and Techniques
.NET Debugging Tips and Techniques
 
Os Selbak
Os SelbakOs Selbak
Os Selbak
 
Analytics tools and Instruments
Analytics tools and InstrumentsAnalytics tools and Instruments
Analytics tools and Instruments
 
Production Debugging at Code Camp Philly
Production Debugging at Code Camp PhillyProduction Debugging at Code Camp Philly
Production Debugging at Code Camp Philly
 

Dernier

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Dernier (20)

Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 

Better Embedded 2013 - Detecting Memory Leaks with Valgrind

  • 1. Detecting Memory Leaks with Valgrind by Rigels Gordani
  • 2. Rigels Gordani Computer Engineer Intecs S.p.A Automotive Unit - In Vehicle Infotainment, - Linux Embedded, - AUTOSAR Products Unit - Porting Linux applications to Windows About me
  • 4. Detecting Memory Leaks with Valgrind Memory errors lead to faults like segmentation faults, which are very common while dealing with pointers in C/C++ programming. Identifying and fixing compilation errors is quite easy, but the task of fixing segmentation faults and memory leaks is very tedious.
  • 5. Detecting Memory Leaks with Valgrind Valgrind is a memory checker, it is designed to be as non-intrusive as possible. It works directly with existing executables. You don’t need to recompile, relink, or otherwise modify the program to be checked.
  • 6. Detecting Memory Leaks with Valgrind Latest stable version as speaking of Valgrind is 3.8.x. The following platforms support Valgrind: - x86 and x86_64 Linux - ARM Linux and ARM Android ( >= 2.3.x) - PPC32 and PPC64 Linux - S390X Linux - MIPS Linux - x86 Android (>= 4.0) - x86 and AMD64 Darwin
  • 7. Detecting Memory Leaks with Valgrind In this presentation we will explore how to use Valgrind to detect memory errors in a program written in C/C++ using MemCheck tool. Apart from MemCheck tool, Valgrind also includes: - thread error detectors, - a cache and branch-prediction profiler, - a call-graph generating cache - and branch-prediction profiler, - a heap profiler and other experimental tools.
  • 8. Detecting Memory Leaks with Valgrind What kind of problems can be detected with Valgrind 's memcheck: 1. Not releasing acquired memory using delete/free. 2. Writing into an array with an index that's out of bounds 3. Trying to reference/dereference a pointer that is not yet initialized.
  • 9. Detecting Memory Leaks with Valgrind 4. Trying to dereference a pointer that is already freed. 5. Passing system call parameters with inadequate buffers for read/write; i.e., if your program makes a system call passing an invalid buffer. 6. Uses of undefined variable values.
  • 10. Detecting Memory Leaks with Valgrind All the previous situations can give rise to memory errors, causing the program to terminate abruptly. This is particularly dangerous in safety and mission-critical systems, where such abrupt program termination can have catastrophic consequences. Hence, it is necessary to detect and resolve such errors that can lead to segmentation faults.
  • 11. Detecting Memory Leaks with Valgrind All the previous situations can give rise to memory The Valgrind open source tool can be used to detect some of these errors by dynamically executing the program. Memory faults may not cause significant damages in small programs, but can be extremely dangerous in safety-critical applications and can have disastrous consequences; for instance, a segmentation fault in a medical application may lead to loss of lives.
  • 12. Detecting Memory Leaks with Valgrind Let's illustrate the usage of Valgrind through the following scenarios: 1. Valgrind command line tool. 2. QtCreator integration of Valgrind. 3. Eclipse integration of Valgrind using LinuxTools.
  • 13. Detecting Memory Leaks with Valgrind 1. Valgrind command line tool. Compile the C or C++ source file with debugging option: $ g++ -g example1.cpp -o example1 // for a C++ file $ gcc -g example1.c -o example1 // for a C file With -g option, you’ll get messages which point directly to the relevant source code lines. Omitting -g options, you'll get only functions name.
  • 14. Detecting Memory Leaks with Valgrind 1. Valgrind command line tool. To analyse the program compiled using Valgrind, run the following command: $ valgrind --tool=memcheck --leak-check=yes ./example1
  • 15. Detecting Memory Leaks with Valgrind 1. Valgrind command line tool. To analyse the program compiled using Valgrind, run the following command: $ valgrind --tool=memcheck --leak-check=yes ./example1
  • 16. Detecting Memory Leaks with Valgrind 1. Valgrind command line tool. $ gcc -g example1.c -o example1 $ valgrind --tool=memcheck --leak-check=yes ./example1 Out of bounds access, C compiler doesn't complain Memory leak
  • 17. Detecting Memory Leaks with Valgrind 1. Valgrind command line tool. ==6287== Memcheck, a memory error detector ==6287== Copyright (C) 2002-2011, and GNU GPL'd, by Julian Seward et al. ==6287== Using Valgrind-3.7.0 and LibVEX; rerun with -h for copyright info ==6287== Command: ./example1 ==6287== ==6287== Invalid write of size 4 ==6287== at 0x400567: main (prova.c:14) ==6287== Address 0x51f1068 is 0 bytes after a block of size 40 alloc'd ==6287== at 0x4C2B3F8: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so) ==6287== by 0x400534: main (prova.c:8) ==6287== ==6287== ==6287== HEAP SUMMARY: ==6287== in use at exit: 40 bytes in 1 blocks ==6287== total heap usage: 1 allocs, 0 frees, 40 bytes allocated ==6287== ==6287== 40 bytes in 1 blocks are definitely lost in loss record 1 of 1 ==6287== at 0x4C2B3F8: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so) ==6287== by 0x400534: main (prova.c:8) ==6287==
  • 18. Detecting Memory Leaks with Valgrind 1. Valgrind command line tool. (continues...) ==6287== LEAK SUMMARY: ==6287== definitely lost: 40 bytes in 1 blocks ==6287== indirectly lost: 0 bytes in 0 blocks ==6287== possibly lost: 0 bytes in 0 blocks ==6287== still reachable: 0 bytes in 0 blocks ==6287== suppressed: 0 bytes in 0 blocks ==6287== ==6287== For counts of detected and suppressed errors, rerun with: -v ==6287== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 2 from 2)
  • 19. Detecting Memory Leaks with Valgrind 2. QtCreator integration of Valgrind. Open QtCreator.  Create a C application project.  Edit the C source file  Compile in Debug Mode  Analyze-> Run Valgrind Memory Analyzer
  • 20. Detecting Memory Leaks with Valgrind 2. QtCreator integration of Valgrind.
  • 21. Detecting Memory Leaks with Valgrind 2. QtCreator integration of Valgrind. Advantages of a GUI solution are obvious here:  Very quick problem identification  Click on the error sends to the line of code with the error  No need to run Valgrind from command line, QtCreator does it
  • 22. Detecting Memory Leaks with Valgrind 3. Eclipse integration of Valgrind using LinuxTools. Need to install LinuxTools from Eclipse components. After installing LinuxTools:  Open Eclipse  Create a new C++ Project.  Edit the C++ file.  Build in Debug Mode  Profile with Valgrind.
  • 23. Detecting Memory Leaks with Valgrind 3. Eclipse integration of Valgrind using LinuxTools.
  • 24. Detecting Memory Leaks with Valgrind Using C++11 smart pointers like unique_ptr<...> They allow you to write code that automatically prevents memory or resource leaks with exception handling. Smart pointer objects are allocated on the stack and whenever the smart pointer object is destroyed, it frees the underlying resource.
  • 25. Detecting Memory Leaks with Valgrind Using C++11 smart pointers like unique_ptr<...>
  • 26. Detecting Memory Leaks with Valgrind Using C++11 smart pointers like unique_ptr<...> $ valgrind --tool=memcheck --leak-check=full ./example_uniq ==30755== Memcheck, a memory error detector ==30755== Copyright (C) 2002-2012, and GNU GPL'd, by Julian Seward et al. ==30755== Using Valgrind-3.8.1 and LibVEX; rerun with -h for copyright info ==30755== Command: ./example_uniq ==30755== main() print() ==30755== ==30755== HEAP SUMMARY: ==30755== in use at exit: 0 bytes in 0 blocks ==30755== total heap usage: 1 allocs, 1 frees, 24 bytes allocated ==30755== ==30755== All heap blocks were freed -- no leaks are possible ==30755== ==30755== For counts of detected and suppressed errors, rerun with: -v ==30755== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 2 from 2)
  • 27. Detecting Memory Leaks with Valgrind Valgrind usage in identifying software security problems Valgrind can identify many of the “Top 25 Most Dangerous Software Errors” listed in http://cwe.mitre.org/top25/#CWE-676 [4]: Buffer Copy without Checking Size of Input ('Classic Buffer Overflow') [20]: Incorrect Calculation of Buffer Size
  • 28. Detecting Memory Leaks with Valgrind Bibliography: 1. www.valgrind.org 2. GNU Linux Application Programming 2ed, Chapter 34 3. The developers guide to debugging , Spinger ,Holtmann, Chapter 4, Fixing memory problems 4. Professional C++, Wiley, ISBN 0470932449 5. Valgrind Advanced Debugging and Profiling for GNU/Linux applications ISBN: 0-9546120-5-1
  • 29. Detecting Memory Leaks with Valgrind Thank you Rigels Gordani rigels_gordani rigels.gordani