Finding Memory Leaks. The new operator and operator new When allocating memory using new, e.g. –Student *ps = new Student(“Yossi Cohen”); –int *pi = new.

Slides:



Advertisements
Similar presentations
Factorial Preparatory Exercise #include using namespace std; double fact(double); int fact(int); int main(void) { const int n=20; ofstream my_file("results.txt");
Advertisements

What's new in Microsoft Visual C Preview
Constructor. 2 constructor The main use of constructors is to initialize objects. A constructor is a special member function, whose name is same as class.
Core Java Lecture 4-5. What We Will Cover Today What Are Methods Scope and Life Time of Variables Command Line Arguments Use of static keyword in Java.
Introduction to Programming Lecture 39. Copy Constructor.
Templated Functions. Overloading vs Templating  Overloaded functions allow multiple functions with the same name.
Chapter 8 Scope, Lifetime and More on Functions. Definitions Scope –The region of program code where it is legal to reference (use) an identifier Three.
Dynamic Allocation Eric Roberts CS 106B February 4, 2013.
Growing Arrays in C Language. When to Use Do not use Growing Sorted Array –O(n 2 ) Operation –Avoid when n is large Use Keep track of a variable –Few.
OBJECT ORIENTED PROGRAMMING Instructor: Rashi Garg Coordinator: Gaurav Saxena.
Writing a Good Program 6. Pointers and Arrays
1 Day 03 Introduction to C. 2 Memory layout and addresses r s int x = 5, y = 10; float f = 12.5, g = 9.8; char c = ‘r’, d = ‘s’;
Pointers: Part I. Why pointers? - low-level, but efficient manipulation of memory - dynamic objects  Objects whose memory is allocated during program.
CS-2303 System Programming Concepts
Lecture 03a: C++ classes Topics: basic classes and objects constructor, destructor Miscellaney An intro to the STL (Standard Template Library)
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
Recap, Test 1 prep, Composition and Inheritance. Dates Test 1 – 12 th of March Assignment 1 – 20 th of March.
Dynamic Memory Allocation The process of allocating memory at run time is known as dynamic memory allocation. C does not Inherently have this facility,
Copyright © 2012 Pearson Education, Inc. Chapter 13: Introduction to Classes.
CS 11 C++ track: lecture 4 Today: More on memory management the stack and the heap inline functions structs vs. classes.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 13: Introduction to Classes.
ITEC 320 C++ Examples.
Copyright  Hannu Laine C++-programming Part 1 Hannu Laine.
1 C++ Classes and Data Structures Jeffrey S. Childs Chapter 5 An Array Class Jeffrey S. Childs Clarion University of PA © 2008, Prentice Hall.
C++ Review (3) Structs, Classes, Data Abstraction.
ACM C++ Tutorial Nathan Ratliff. Development Environments Windows – Microsoft Visual C++ Note: It’s not ansi standard Linux / Unix – GCC / G++
 Managing the heap  Resource acquisition is initialization (RAII)  Overriding operator new and delete  Class-based memory pools.
Dynamically Allocated Arrays December 4, Skip the Rest of this PowerPoint.
Chapter 8 Scope of variables Name reuse. Scope The region of program code where it is legal to reference (use) a variable The scope of a variable depends.
Savitch - Chapters 9&11 CS Pointers A pointer holds the memory address of a variable. Main Memory Byte # Byte # Byte # Byte.
Object Oriented Programming Elhanan Borenstein Lecture #3 copyrights © Elhanan Borenstein.
Monday, Feb 3, 2003Kate Gregory with material from Deitel and Deitel Week 5 Lab 1 comments Hand in Lab 2 Questions from Last Week Classes continued Lab.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Stacks.
Variables and Data Types.  Variable: Portion of memory for storing a determined value.  Could be numerical, could be character or sequence of characters.
Review of Last Lecture. What we have learned last lecture? What does a constructor do? What is the way to define a constructor? Can it be defined under.
1 Functions in C++ Default arguments Overloading Inlining Call-by-reference Scope of variables, static, extern namespace new and delete assert.
1 More Operator Overloading Chapter Objectives You will be able to: Define and use an overloaded operator to output objects of your own classes.
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
Functions Illustration of: Pass by value, reference Scope Allocation Reference: See your CS115/215 textbook.
System Programming Practical Session 7 C++ Memory Handling.
LECTURE LECTURE 11 Constructors and destructors Copy constructor Textbook: p , 183.
Classes, Arrays & Pointers. Compiler & Linker expectations file1.cppfile2.cppfilen.cpp …. file1.ofile2.ofilen.o …. Linker application (executable) Compiler.
EEL 3801 C++ as an Enhancement of C. EEL 3801 – Lotzi Bölöni Comments  Can be done with // at the start of the commented line.  The end-of-line terminates.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 15. Dictionaries (1): A Key Table Class.
1 Classes classes and objects - from object-oriented programming point of view class declaration class class_name{ data members … methods (member functions)
1 Memory as byte array Pointers Arrays relationship to pointers Operator ‘new’ Operator ‘delete’ Copy ctor Assignment operator ‘this’ const pointer Allocating.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 13: Introduction to Classes.
Array and Pointers An Introduction Unit Unit Introduction This unit covers the usage of pointers and arrays in C++
Lecture 01d: C++ review Topics: functions scope / lifetime preprocessor directives header files C structures ("simple classes")
1 Compiler directive: #define, usage 1 #include using namespace std; #define TAX //double TAX=0.08; #define LAST_NAME "Li" #define FIRST_NAME "Dennis"
Debugging Malloc Lab Detecting Memory-Related Errors.
Defining Data Types in C++ Part 2: classes. Quick review of OOP Object: combination of: –data structures (describe object attributes) –functions (describe.
C++ Programming Michael Griffiths Corporate Information and Computing Services The University of Sheffield
Abstract classes only used as base class from which other classes can be inherit cannot be used to instantiate any objects are incomplete Classes that.
C++ Lesson 1.
Pointer to an Object Can define a pointer to an object:
Procedural and Object-Oriented Programming
Pointers and Dynamic Arrays
Submission Example May 14, 2018
#define #include<iostream> using namespace std; #define GO
Default Constructors A default constructor is a constructor that takes no arguments. If you write a class with no constructor at all, C++ will write a.
group work #hifiTeam
Reserved Words.
Dynamic Memory Allocation Reference Variables
Built-In (a.k.a. Native) Types in C++
Programming Language C Language.
Pointer & Memory Allocation Review
Recitation Course 0603 Speaker: Liu Yu-Jiun.
CS 144 Advanced C++ Programming April 30 Class Meeting
Presentation transcript:

Finding Memory Leaks

The new operator and operator new When allocating memory using new, e.g. –Student *ps = new Student(“Yossi Cohen”); –int *pi = new int[100]; The new operator (or new[] operator) is called The new ( new[] ) operator –Calls operator new ( operator new[] ) to allocate memory –Calls a constructor (default ctor, for arrays)

Overloading operator new The new operator cannot be overloaded operator new and operator new[] can be overloaded in two ways: –For a given class –As global operators, which will apply for all types and classes for which these operators were not overloaded in the class. When overloading operator new, one should also overload operator new[]. operator new can be overloaded with extra parameters

The delete operator and operator delete When releasing memory using delete, e.g. –Delete ps; –delete []pi; The delete operator (or delete[] operator) is called The delete ( delete[] ) operator –Calls the destructor (destructors for arrays) –Calls operator delete ( operator delete[] ) to release memory

Overloading operator delete The delete operator cannot be overloaded operator delete and operator delete[] can be overloaded in two ways: –For a given class –As global operators, which will apply for all types and classes for which these operators were not overloaded in the class. When overloading operator delete, one should also overload operator delete[]. operator delete can be overloaded with extra parameters

Overloading operator new and operator delete operator new and operator delete can be overloaded to keep track of all memory allocations in a program In the following example the global versions of these operators are overloaded

// CatchMemoryLeak.h Created by Yosi Halakhmi, private consultant #ifndef CATCHMEMORYLEAK_H #define CATCHMEMORYLEAK_H #include void saveInStorage(unsigned long addr, unsigned long nBytes, const char *fname, unsigned long lnum); void removeFromStorage(unsigned long addr); void reportUnreleasedHeap(); #ifdef _DEBUG inline void * operator new(unsigned int size, const char *fileName, int line) { void *ptr = (void *)malloc(size); saveInStorage((unsigned long)ptr, size, fileName, line); return(ptr); } inline void * operator new[](unsigned int size, const char * fileName, int line) { void *ptr = (void *)malloc(size); saveInStorage((unsigned long)ptr, size, fileName, line); return(ptr); }

inline void operator delete(void* ptr) { removeFromStorage((unsigned long)ptr); free(ptr); } inline void operator delete[](void* ptr) { removeFromStorage((unsigned long)ptr); free(ptr); } #endif// _DEBUG #ifdef DEBUG_NEW // MFC macro #undefDEBUG_NEW #endif #ifdef _DEBUG #define new new(__FILE__, __LINE__) #endif #endif// CATCHMEMORYLEAK_H

// CatchMemoryLeak.cpp #include using namespace std; struct HeapInfo_s { stringfileName; unsigned longlineNo; unsigned longadrInHeap; unsigned longnBytes; }; typedef map heapStorage_t; heapStorage_t* heapStorage; // global variable is initialized to 0 void saveInStorage(unsigned long addr, unsigned long nBytes, const char* fileName, unsigned long lineNo) { HeapInfo_s* hInfo; if(!heapStorage) { heapStorage = new(heapStorage_t); } hInfo = new (HeapInfo_s); hInfo->adrInHeap = addr; hInfo->fileName = fileName; hInfo->lineNo = lineNo; hInfo->nBytes = nBytes; (*heapStorage)[addr] = hInfo; }

void removeFromStorage(unsigned long addr) { if( heapStorage) { heapStorage_t::iterator itor; itor = heapStorage->find(addr); if (itor != heapStorage->end() ) { heapStorage->erase((itor)); } void reportUnreleasedHeap() { ofstream ofs("Leaks.txt"); if( heapStorage) { heapStorage_t::iterator itor; for(itor = heapStorage->begin(); itor != heapStorage->end(); ++itor) { ofs fileName << endl; ofs lineNo << endl; ofs << "Number of unreleased bytes : " nBytes << endl; ofs << endl; }

// TestMemoryLeak.cpp #include #include "CatchMemoryLeak.h" using namespace std; class X { char c; int y; public: X(char a=0, int b=0):c(a),y(b){} }; void func() { float* pf = new float; // memory leak } int main() { char* ip = new char; int* ip1 = new int[100]; int* ip2 = (int*)malloc(50*sizeof(int)); X* px=new X(‘a’,1); // memory leak func(); delete ip; delete []ip1; reportUnreleasedHeap(); return 0; }

File Name : testmemoryleak.cpp Line No : 23 Number of unreleased bytes : 8 File Name : testmemoryleak.cpp Line No : 15 Number of unreleased bytes : 4 Report: Alignment of int

Discussion How can we keep track of possible deletions of already freed memory? How can we keep track of overwriting data below or above the allocated block?