SlideShare una empresa de Scribd logo
1 de 29
Descargar para leer sin conexión
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

Más contenido relacionado

La actualidad más candente

Linux kernel tracing
Linux kernel tracingLinux kernel tracing
Linux kernel tracingViller Hsiao
 
Xen on ARM for embedded and IoT: from secure containers to dom0less systems
Xen on ARM for embedded and IoT: from secure containers to dom0less systemsXen on ARM for embedded and IoT: from secure containers to dom0less systems
Xen on ARM for embedded and IoT: from secure containers to dom0less systemsStefano Stabellini
 
ACPI Debugging from Linux Kernel
ACPI Debugging from Linux KernelACPI Debugging from Linux Kernel
ACPI Debugging from Linux KernelSUSE Labs Taipei
 
Tracing MariaDB server with bpftrace - MariaDB Server Fest 2021
Tracing MariaDB server with bpftrace - MariaDB Server Fest 2021Tracing MariaDB server with bpftrace - MariaDB Server Fest 2021
Tracing MariaDB server with bpftrace - MariaDB Server Fest 2021Valeriy Kravchuk
 
C/C++プログラマのための開発ツール
C/C++プログラマのための開発ツールC/C++プログラマのための開発ツール
C/C++プログラマのための開発ツールMITSUNARI Shigeo
 
Linux Instrumentation
Linux InstrumentationLinux Instrumentation
Linux InstrumentationDarkStarSword
 
Return to dlresolve
Return to dlresolveReturn to dlresolve
Return to dlresolveAngel Boy
 
Staring into the eBPF Abyss
Staring into the eBPF AbyssStaring into the eBPF Abyss
Staring into the eBPF AbyssSasha Goldshtein
 
LinuxCon 2015 Linux Kernel Networking Walkthrough
LinuxCon 2015 Linux Kernel Networking WalkthroughLinuxCon 2015 Linux Kernel Networking Walkthrough
LinuxCon 2015 Linux Kernel Networking WalkthroughThomas Graf
 
malloc & vmalloc in Linux
malloc & vmalloc in Linuxmalloc & vmalloc in Linux
malloc & vmalloc in LinuxAdrian Huang
 
用Raspberry Pi 學Linux I2C Driver
用Raspberry Pi 學Linux I2C Driver用Raspberry Pi 學Linux I2C Driver
用Raspberry Pi 學Linux I2C Driver艾鍗科技
 
組み込みでこそC++を使う10の理由
組み込みでこそC++を使う10の理由組み込みでこそC++を使う10の理由
組み込みでこそC++を使う10の理由kikairoya
 
Kernel Recipes 2019 - ftrace: Where modifying a running kernel all started
Kernel Recipes 2019 - ftrace: Where modifying a running kernel all startedKernel Recipes 2019 - ftrace: Where modifying a running kernel all started
Kernel Recipes 2019 - ftrace: Where modifying a running kernel all startedAnne Nicolas
 
Physical Memory Models.pdf
Physical Memory Models.pdfPhysical Memory Models.pdf
Physical Memory Models.pdfAdrian Huang
 
ELFの動的リンク
ELFの動的リンクELFの動的リンク
ELFの動的リンク7shi
 
Fun with Network Interfaces
Fun with Network InterfacesFun with Network Interfaces
Fun with Network InterfacesKernel TLV
 
eBPF - Observability In Deep
eBPF - Observability In DeepeBPF - Observability In Deep
eBPF - Observability In DeepMydbops
 

La actualidad más candente (20)

Linux kernel tracing
Linux kernel tracingLinux kernel tracing
Linux kernel tracing
 
Xen on ARM for embedded and IoT: from secure containers to dom0less systems
Xen on ARM for embedded and IoT: from secure containers to dom0less systemsXen on ARM for embedded and IoT: from secure containers to dom0less systems
Xen on ARM for embedded and IoT: from secure containers to dom0less systems
 
ACPI Debugging from Linux Kernel
ACPI Debugging from Linux KernelACPI Debugging from Linux Kernel
ACPI Debugging from Linux Kernel
 
Tracing MariaDB server with bpftrace - MariaDB Server Fest 2021
Tracing MariaDB server with bpftrace - MariaDB Server Fest 2021Tracing MariaDB server with bpftrace - MariaDB Server Fest 2021
Tracing MariaDB server with bpftrace - MariaDB Server Fest 2021
 
C/C++プログラマのための開発ツール
C/C++プログラマのための開発ツールC/C++プログラマのための開発ツール
C/C++プログラマのための開発ツール
 
Linux Instrumentation
Linux InstrumentationLinux Instrumentation
Linux Instrumentation
 
Return to dlresolve
Return to dlresolveReturn to dlresolve
Return to dlresolve
 
llvm入門
llvm入門llvm入門
llvm入門
 
Staring into the eBPF Abyss
Staring into the eBPF AbyssStaring into the eBPF Abyss
Staring into the eBPF Abyss
 
LinuxCon 2015 Linux Kernel Networking Walkthrough
LinuxCon 2015 Linux Kernel Networking WalkthroughLinuxCon 2015 Linux Kernel Networking Walkthrough
LinuxCon 2015 Linux Kernel Networking Walkthrough
 
malloc & vmalloc in Linux
malloc & vmalloc in Linuxmalloc & vmalloc in Linux
malloc & vmalloc in Linux
 
用Raspberry Pi 學Linux I2C Driver
用Raspberry Pi 學Linux I2C Driver用Raspberry Pi 學Linux I2C Driver
用Raspberry Pi 學Linux I2C Driver
 
組み込みでこそC++を使う10の理由
組み込みでこそC++を使う10の理由組み込みでこそC++を使う10の理由
組み込みでこそC++を使う10の理由
 
Kernel Recipes 2019 - ftrace: Where modifying a running kernel all started
Kernel Recipes 2019 - ftrace: Where modifying a running kernel all startedKernel Recipes 2019 - ftrace: Where modifying a running kernel all started
Kernel Recipes 2019 - ftrace: Where modifying a running kernel all started
 
Physical Memory Models.pdf
Physical Memory Models.pdfPhysical Memory Models.pdf
Physical Memory Models.pdf
 
ELFの動的リンク
ELFの動的リンクELFの動的リンク
ELFの動的リンク
 
Fun with Network Interfaces
Fun with Network InterfacesFun with Network Interfaces
Fun with Network Interfaces
 
Effective CMake
Effective CMakeEffective CMake
Effective CMake
 
eBPF - Observability In Deep
eBPF - Observability In DeepeBPF - Observability In Deep
eBPF - Observability In Deep
 
Gcc porting
Gcc portingGcc porting
Gcc porting
 

Destacado

Physics and Marketing
Physics and MarketingPhysics and Marketing
Physics and MarketingTED Talks
 
10 myths about psychology
10 myths about psychology10 myths about psychology
10 myths about psychologyTED Talks
 
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 FutureArturo Pelayo
 
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 CarsLinkedIn
 
Hype vs. Reality: The AI Explainer
Hype vs. Reality: The AI ExplainerHype vs. Reality: The AI Explainer
Hype vs. Reality: The AI ExplainerLuminary Labs
 
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 2017Drift
 

Destacado (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
 

Similar a Better Embedded 2013 - Detecting Memory Leaks with Valgrind

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 ValgrindRapidValue
 
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 analysisRaghu Palakodety
 
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 corruptionlinuxlab_conf
 
Crash dump analysis - experience sharing
Crash dump analysis - experience sharingCrash dump analysis - experience sharing
Crash dump analysis - experience sharingJames 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_valgrindRaghu Palakodety
 
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 workshopSlawomir Jasek
 
Android tools for testers
Android tools for testersAndroid tools for testers
Android tools for testersMaksim Kovalev
 
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 ComponentsPVS-Studio
 
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
 
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...Minsk Linux User Group
 
What
WhatWhat
Whatanity
 
.NET Debugging Tips and Techniques
.NET Debugging Tips and Techniques.NET Debugging Tips and Techniques
.NET Debugging Tips and TechniquesBala Subra
 
.Net Debugging Techniques
.Net Debugging Techniques.Net Debugging Techniques
.Net Debugging TechniquesBala Subra
 
Analytics tools and Instruments
Analytics tools and InstrumentsAnalytics tools and Instruments
Analytics tools and InstrumentsKrunal Soni
 
Production Debugging at Code Camp Philly
Production Debugging at Code Camp PhillyProduction Debugging at Code Camp Philly
Production Debugging at Code Camp PhillyBrian Lyttle
 
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...Maarten Balliauw
 

Similar a 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 Tips and Techniques
.NET Debugging Tips and Techniques.NET Debugging Tips and Techniques
.NET Debugging Tips and Techniques
 
.Net Debugging Techniques
.Net Debugging Techniques.Net Debugging Techniques
.Net Debugging 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...
 

Último

How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 

Último (20)

How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck 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