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

SDC 3rd 최흥배님 - Boost.multi_index 사용하기
SDC 3rd 최흥배님 - Boost.multi_index 사용하기SDC 3rd 최흥배님 - Boost.multi_index 사용하기
SDC 3rd 최흥배님 - Boost.multi_index 사용하기
OnGameServer
 
MPI Introduction
MPI IntroductionMPI Introduction
MPI Introduction
Rohit Banga
 

Tendances (20)

Namespace in C++ Programming Language
Namespace in C++ Programming LanguageNamespace in C++ Programming Language
Namespace in C++ Programming Language
 
A look into the sanitizer family (ASAN & UBSAN) by Akul Pillai
A look into the sanitizer family (ASAN & UBSAN) by Akul PillaiA look into the sanitizer family (ASAN & UBSAN) by Akul Pillai
A look into the sanitizer family (ASAN & UBSAN) by Akul Pillai
 
MacOS memory allocator (libmalloc) Exploitation
MacOS memory allocator (libmalloc) ExploitationMacOS memory allocator (libmalloc) Exploitation
MacOS memory allocator (libmalloc) Exploitation
 
Introduction to Python programming
Introduction to Python programmingIntroduction to Python programming
Introduction to Python programming
 
Effective testing with pytest
Effective testing with pytestEffective testing with pytest
Effective testing with pytest
 
What Can Compilers Do for Us?
What Can Compilers Do for Us?What Can Compilers Do for Us?
What Can Compilers Do for Us?
 
Java - Exception Handling Concepts
Java - Exception Handling ConceptsJava - Exception Handling Concepts
Java - Exception Handling Concepts
 
Q2.12: Debugging with GDB
Q2.12: Debugging with GDBQ2.12: Debugging with GDB
Q2.12: Debugging with GDB
 
C++11 & C++14
C++11 & C++14C++11 & C++14
C++11 & C++14
 
Semmle Codeql
Semmle Codeql Semmle Codeql
Semmle Codeql
 
Python Basics
Python BasicsPython Basics
Python Basics
 
SDC 3rd 최흥배님 - Boost.multi_index 사용하기
SDC 3rd 최흥배님 - Boost.multi_index 사용하기SDC 3rd 최흥배님 - Boost.multi_index 사용하기
SDC 3rd 최흥배님 - Boost.multi_index 사용하기
 
Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
 
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
 
OpenStack Oslo Messaging RPC API Tutorial Demo Call, Cast and Fanout
OpenStack Oslo Messaging RPC API Tutorial Demo Call, Cast and FanoutOpenStack Oslo Messaging RPC API Tutorial Demo Call, Cast and Fanout
OpenStack Oslo Messaging RPC API Tutorial Demo Call, Cast and Fanout
 
Java History
Java HistoryJava History
Java History
 
MPI Introduction
MPI IntroductionMPI Introduction
MPI Introduction
 
Insecure coding in C (and C++)
Insecure coding in C (and C++)Insecure coding in C (and C++)
Insecure coding in C (and C++)
 
Implementing a JavaScript Engine
Implementing a JavaScript EngineImplementing a JavaScript Engine
Implementing a JavaScript Engine
 
Kotlin
KotlinKotlin
Kotlin
 

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
 
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
 
JetBrains Day Seoul - Exploring .NET’s memory management – a trip down memory...
JetBrains Day Seoul - Exploring .NET’s memory management – a trip down memory...JetBrains Day Seoul - Exploring .NET’s memory management – a trip down memory...
JetBrains Day Seoul - Exploring .NET’s memory management – a trip down memory...
 

Dernier

Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
panagenda
 

Dernier (20)

Google I/O Extended 2024 Warsaw
Google I/O Extended 2024 WarsawGoogle I/O Extended 2024 Warsaw
Google I/O Extended 2024 Warsaw
 
Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...
Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...
Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...
 
2024 May Patch Tuesday
2024 May Patch Tuesday2024 May Patch Tuesday
2024 May Patch Tuesday
 
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
 
FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...
FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...
FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...
 
Linux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdf
Linux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdfLinux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdf
Linux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdf
 
TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...
TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...
TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...
 
Overview of Hyperledger Foundation
Overview of Hyperledger FoundationOverview of Hyperledger Foundation
Overview of Hyperledger Foundation
 
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdfSimplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
 
Intro to Passkeys and the State of Passwordless.pptx
Intro to Passkeys and the State of Passwordless.pptxIntro to Passkeys and the State of Passwordless.pptx
Intro to Passkeys and the State of Passwordless.pptx
 
State of the Smart Building Startup Landscape 2024!
State of the Smart Building Startup Landscape 2024!State of the Smart Building Startup Landscape 2024!
State of the Smart Building Startup Landscape 2024!
 
Collecting & Temporal Analysis of Behavioral Web Data - Tales From The Inside
Collecting & Temporal Analysis of Behavioral Web Data - Tales From The InsideCollecting & Temporal Analysis of Behavioral Web Data - Tales From The Inside
Collecting & Temporal Analysis of Behavioral Web Data - Tales From The Inside
 
Using IESVE for Room Loads Analysis - UK & Ireland
Using IESVE for Room Loads Analysis - UK & IrelandUsing IESVE for Room Loads Analysis - UK & Ireland
Using IESVE for Room Loads Analysis - UK & Ireland
 
WebAssembly is Key to Better LLM Performance
WebAssembly is Key to Better LLM PerformanceWebAssembly is Key to Better LLM Performance
WebAssembly is Key to Better LLM Performance
 
ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...
ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...
ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...
 
Long journey of Ruby Standard library at RubyKaigi 2024
Long journey of Ruby Standard library at RubyKaigi 2024Long journey of Ruby Standard library at RubyKaigi 2024
Long journey of Ruby Standard library at RubyKaigi 2024
 
Where to Learn More About FDO _ Richard at FIDO Alliance.pdf
Where to Learn More About FDO _ Richard at FIDO Alliance.pdfWhere to Learn More About FDO _ Richard at FIDO Alliance.pdf
Where to Learn More About FDO _ Richard at FIDO Alliance.pdf
 
Event-Driven Architecture Masterclass: Challenges in Stream Processing
Event-Driven Architecture Masterclass: Challenges in Stream ProcessingEvent-Driven Architecture Masterclass: Challenges in Stream Processing
Event-Driven Architecture Masterclass: Challenges in Stream Processing
 
Working together SRE & Platform Engineering
Working together SRE & Platform EngineeringWorking together SRE & Platform Engineering
Working together SRE & Platform Engineering
 
AI mind or machine power point presentation
AI mind or machine power point presentationAI mind or machine power point presentation
AI mind or machine power point presentation
 

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