• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
Memory Management In C++
 

Memory Management In C++

on

  • 5,400 views

This is one of my first presentations on Advanced C++ stuff

This is one of my first presentations on Advanced C++ stuff

Statistics

Views

Total Views
5,400
Views on SlideShare
5,388
Embed Views
12

Actions

Likes
5
Downloads
104
Comments
0

1 Embed 12

http://www.linkedin.com 12

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    Memory Management In C++ Memory Management In C++ Presentation Transcript

    • Memory Management in C++ Advanced techniques and idioms -ShriKant Vashishtha
      • Distinct memory areas in C++
      • Const Data
      • Stack
      • Free Store
      • Heap
      • Global/Static
    • Distinct Memory areas in C++
      • Const Data
      • Stores string literals and other data whose values are known at compile time
      • No objects of class type
      • Available during entire lifetime of the program
      • read-only data?
    • Distinct Memory areas in C++
      • Stack
      • Stores automatic variables
      • Allocation is much faster than dynamic memory allocation - why?
      • Objects are constructed immediately after memory is allocated and destroyed before memory is deallocated.
    • Distinct Memory areas in C++
      • Free Store
      • One of dynamic memory areas.
      • Allocated/freed by new/delete.
      • Objects are constructed after memory is allocated and are destroyed before memory is deallocated…then what?
      • What about Object manipulation at the time of memory allocation?
    • Distinct Memory areas in C++
      • Heap
      • Allocated/freed by malloc/free and their variants.
      • Not same as free store…why?
      • For class types the memory can be allocated and deallocated by placement-new and explicit destruction.
    • Distinct Memory areas in C++
      • Global/Static
      • Storage allocated at program startup.
      • May not be initialized until after program has started execution.
      • The order of initialization of global variables across translation units is not defined.
      • Object access rules as are of Free Store.
    • Pointers Vs References
      • Both do similar things.
      • There is no such thing as a null reference. Must always refer to some object.
      • Pointers can be null.
      • What about this..
      • char * pc=0; //set pointer to null
      • char & rc = *pc; //make reference refer to dereferenced null pointer
    • Pointers Vs References
      • Reference must initialized.
      • String & rs; //error
      • string s(“xyz”);
      • string & rs = s; //OK. rs refers to s;
      • No such restriction for pointers
      • string * ps; //uninitialized pointer
      • //valid but risky.
    • Pointers Vs References
      • Pointers may be reassigned to refer to different objects. A reference always refers to the object with which it is initialized.
      • string s1(“Ram”);
      • string s2(“Krishna”);
      • string & rs = s1;
      • string * ps = &s1; //rs still refers to s1 but s1’s value is
      • //now “Krishna”
      • rs=s2;
      • ps = &s2; //ps now points to s2. s1 is unchanged.
    • Conclusions: Pointers Vs References
      • References are more efficient.
      • void func (const string & s){
      • cout << s;
      • }
      • Vs.
      • void func2(const string * ps){
      • if(ps){
      • cout << *ps;
      • }
      • }
    • Conclusions: Pointers Vs References
      • Use a pointer whenever we need to take into account the possibility that there’s nothing to refer to or whenever we need to be able to refer to different things at different times.
      • References can be used when we know that there is something to refer to and we know that we’ll never want to refer to something else.
    • Conclusions: Pointers Vs References
      • Use references while implementing operators whose syntactic requirements make the use of pointers undesirable.
      • vector<int> v(10);
      • v[5] = 10; //the target of this assignment
      • //is the return value of operator []
      • Vs
      • *v[5] = 10;
    • ‘new’ operator
      • string * ps = new string(“sample”);
      • new operator does two fold work. Allocates memory to hold an object of the ‘string’ type. Calls a constructor to initialize an object in the memory allocated.
      • This semantics cannot be changed.
      • What we can change is how the memory for an object is allocated. How?
    • ‘ new’ operator Vs operator new
      • new operator calls a function to allocate memory and we can rewrite or overload(????) that function to change its behavior. The name of the function is operator new.
      • void * operator new(size_t size);
      • void * rawmemory = operator new(sizeof(string));
      • We can overload operator new by adding additional parameters, but the first parameter must always be of type size_t.
    • ‘ new’ operator Vs operator new
      • string * ps = new string(“sample”);
      • more or less corresponds to
      • void * memory = operator new(sizeof(string));
      • call string::string(“sample”) on *memory;
      • string *ps = static_cast<string *>(memory);
      • Second step involves calling constructor which programmer is prohibited from doing. Why?
    • ‘ new’ operator Vs operator new
      • Constructor involves necessary steps to initialize the object (including vtbl initialization).
    • Placement new
      • A special version of operator new.
      • There are times when we really want to call a constructor directly. When??
      • When we have some raw memory that’s already been allocated and we need to construct an object in the memory we have.
    • Placement new
      • ClassA{
      • public:
      • ClassA(int a);
      • };
      • ClassA * getClassAInBuff(void * buffer, int a){
      • return new(buffer)ClassA(a);
      • }
      • This operator new is placement new and looks like this:
      • void * operator new(size_t, void * location){
      • return location;
      • }
    • Summary: new operator Vs operator new Vs placement new
      • To create an object on free store, use the new operator.
      • To allocate memory only, call operator new. No constructor will be called.
      • For customization of memory allocation write your on operator new and use the new operator.
      • To construct an object in memory we have already got a pointer to, use placement new.
    • The C++ Object Model
      • Class Point{
      • public:
      • Point(float val);
      • virtual ~Point();
      • float x() const;
      • static int PointCount();
      • protected:
      • virtual ostream & print(ostream & os)const;
      • float _x;
      • static int _point_count;
      • };
      Float_x ---------------------- __vptr__Point --------------------- --------------------- Point::~Point() Point::print(ostream &) static int Point:: _point_count static int Point::PointCount() Point pt; Virtual table for Point type_info for Point Point:: Point(float) Float Point::x()
    • The C++ Object Model
      • Nonstatic data members are allocated directly within each class object.
      • Static data members are stored outside the individual class object.
      • Static and nonstatic member functions are also hoisted outside the class object.
      • Virtual functions
        • A table of pointers to virtual functions is generated for each class object (called virtual table).
        • Single pointer to the associated virtual table inserted in each class object. Handled by class constructor, destructor and copy assignment operator.
        • The type_info object associated with each class in support of RTTI is also addressed in virtual table.
    • C++ Object Model: Evaluation
      • Strength is space and runtime efficiency.
      • Drawback is the need to recompile unmodified code that makes use of an object of a class for which there has been any modification of the nonstatic data members.
    • C++ Object Model: Inheritance
      • class Animal{ … };
      • class Bird : public Animal{ … };
      • class Parrot:public Bird{ … };
      • class iostream: public istream, public ostream { …};
      • class istream : virtual public ios { … };
      • class ostream : virtual public ios { … };
      • The data members of the base class subobject are directly stored in within the derived class object.
      • For virtual inheritance only a single instance of the base class is maintained irrespective of how many times it is derived.
      • The support for virtual base class adds a pointer into the derived class.
      The most compact and the most efficient access of base class data members Drawback: Any change to data members requires recompiling
    • C++ Object Model: Object Mechanics
      • X foobar(){
      • X xx;
      • X *px = new X;
      • //foo is a virtual //function
      • xx.foo();
      • px->foo();
      • delete px;
      • return xx;
      • }
      • void foobar(X & _result){
      • _result.X::X();
      • px = _new(sizeof(X));
      • if(px)
      • px->X::X();
      • foo(&_result);
      • { *px->_vtbl[2])(px);
      • if(px != 0){
      • (*px->vtbl[1]) (px); //destructor
      • _delete(_px);
      • }
      • return;
      • };
      expand X * px = new X 1. construct _result 2. result replaces local xx expand xx.foo(): suppress virtual mechanics expand px->foo() using virtual mechanics expand delete px;
    • The type of a Pointer
      • ZooAnimal *px;
      • int * pi;
      • Array< string > *pta;
      • What’s the difference between these three pointers?
      • What address space does a void * pointer holds memory location 1000 span???
      • There is no difference in terms of memory requirements. All they need is a machine address to get allocated (which is 4 bytes normally).
      • No difference in terms of representation of the pointer nor in addresses the pointers may hold.
      • The difference lies in the type of the object being addressed.
      • Type of a pointer instructs the compiler as to how to interpret the memory found at a particular address and also just how much memory that interpretation should span.
      Can only hold an address and not actually operate on the object it addresses
    • Object deletion and Memory deallocation
      • To avoid resource leaks, every dynamic allocation must be matched by equal and opposite deallocation.
      • String * ps = new string();
      • ..
      • delete ps;
      • corresponds to
      • ps->~string(); //calls the object’s destructor
      • operator delete(ps); //deallocate the memory the object occupied.
    • Object deletion and Memory deallocation
      • If placement new operator is used to create an object in some memory, we should avoid using delete operator to deallocate the memory. Why??
    • Object deletion and Memory deallocation
      • void * mallocshared(size_t size);
      • void freeshared(void * memory);
      • void * memory = mallocShared(sizeof(ClassA));
      • ClassA * pa = new(memory) ClassA(2);
      • delete pa; //undefined!!!! Sharedmemory came
      • //from mallocShared not operator new
      • pa->~ClassA();//fine
      • freeShared(pa);//fine
    • operator delete function
      • o perator delete(ps);
      • void operator delete(void * memoryToBeDeallocated);
      • operator delete to delete operator is analogous to operator new for new operator.
      • The memory deallocation allocated by operator new is performed by the operator delete function.
    • C++ equivalent of malloc-free
      • void * buffer = operator new(50*sizeof(char));
      • operator delete(buffer);
    • Arrays
      • void * buffer = operator new(50*sizeof(char));
      • operator delete(buffer);
    • Why overload new/delete operator?
      • The new operator must have its equivalent corresponding delete operator in all cases.
    • Common memory problems
      • A) Memory allocation conflict
      • 1.char *a;
      • a = new char;
      • free(a);
      • 2.char *a;
      • a = (char *) malloc(1);
      • delete a;
      • B) Copying pointer which is out-of-range
      • char *a, *b;
      • a = new char[10];
      • b = a + 20;
    • Common memory problems
      • C) Inconsistent usage of delete operator
      • 1. int *a = new int [5];
      • delete a;
      • 2. int * a = new int;
      • delete [] a;
      • D) Writing to a dangling pointer
      • char *a = (char *)malloc(10);
      • free(a);
      • *a = 'x';
      • E) Freeing memory block from body
      • char *a = (char *)malloc(10);
      • free(a+1);
    • Common memory problems
      • C) Writing to a NULL pointer
      • int *a;
      • int main(){
      • *a = 123;
      • return (0);
      • }
      • D) Writing overflows memory
      • int main(){
      • int junk;
      • char a[10];
      • strcpy(a, &quot;A simple test&quot;);
      • return (0);
      • }
    • Common memory problems
      • F) Memory leaked leaving scope
      • #include <string.h>
      • union S1 {
      • char *cp;
      • S1() { cp=new char[10]; }
      • S1(char *p) {
      • cp=new char[10];
      • strcpy(cp,p);
      • }
      • S1(S1 &s) {
      • cp=new char[10];
      • strcpy(cp,s.cp);
      • }
      • void mf(char *p){ strcpy(cp,p);}
      • };
      • void foo() {
      • S1 s1,s2(&quot;Hello &quot;),s3=s2;
      • s1.mf(&quot;SADF&quot;);
      • s3.mf(&quot;World&quot;);
      • }
      • int main() {
      • foo();
      • return(0);
      • }
    • Common memory problems
      • F) Reading overflows memory
      • 1. int main() {
        • char *a = &quot;TEST&quot;;
        • char b[20];
        • memcpy(b, a, sizeof(b));
        • return (0);
        • }
      • 2. int main(){
        • char junk;
        • char b[8];
        • strncpy(b, &quot;This is a test&quot;, sizeof(b));
        • printf(&quot;%s &quot;, b);
        • return (0);
        • }
      • 3. class small{
        • public:
        • int x;
        • };
        • class big : public small{
        • public:
        • double y;
        • };
        • int main(){
        • small *var1;
        • big *var2;
        • double d;
        • var1 = new small;
        • var2 = (big *) var1;
        • d = var2->y;
        • return 0;
        • }
    • Problems with Pointer
      • We really don’t like them much anyway.
      • Allocation on the free store has to be associated with delete operator wherever we exit from the scope normally or abnormally.
      • Double-deallocation/heap corrupting
      • Memory leaks
      • Dangling pointers
    • Solutions to the problems with Pointers
    • Use Destructors
      • class ALA{
      • public:
      • virtual void processAdoption()=0;
      • };
      • class Puppy: public ALA{
      • public:
      • virtual void processAdoption();
      • ...
      • };
      • class Kitten:public ALA{
      • public:
      • virtual void processAdoption();
      • ...
      • };
      • ALA * readALA(istream &s);
      • void processAdoptions(istream & dataSource{
      • while(dataSource){
      • ALA *pa = readALA(dataSource);
      • pa->processAdoption();
      • delete pa;
      • }
      • }
      Read animal info from istream object and return a pointer to the object of appropriate ALA type Can lead to resource leak in exceptional conditions.
    • Use Destructors
      • Option 1
      • void processAdoptions(istream & dataSource){
      • while(dataSource){
      • ALA *pa = readALA(dataSource);
      • try{
      • pa->processAdoption();
      • }
      • catch(…){
      • delete pa;
      • throw;
      • }
      • delete pa;
      • }
      • }
      • Problems
        • Code is littered with try and catch blocks.
        • Duplicate cleanup.
        • In any case whether exceptional or by a normal return, we need to delete pa.
        • Solution can be to move cleanup code in the destructor of a local object of processAdoptions().
    • Use Destructors
      • Option 1
      • void processAdoptions(istream & dataSource){
      • while(dataSource){
      • auto_ptr<ALA> pa(readALA(dataSource));
      • pa->processAdoption();
      • }
      • }
      • template<class T>
      • class auto_ptr{
      • public:
      • auto_ptr(T *p = 0):ptr(p) {}
      • ~auto_ptr() { delete ptr; }
      • private:
      • T * ptr;
      • };
      • Advantages
        • Resource is deleted automatically whenever object goes out of scope.
        • No resource leaks in exceptional or normal conditions.
      • Problems
        • Cannot be applied for arrays.
      Save ptr to object delete ptr to object
    • Smart Pointers(auto_ptr template)
      • Option 1
      • void processAdoptions(istream & dataSource){
      • while(dataSource){
      • auto_ptr<ALA> pa(readALA(dataSource));
      • pa->processAdoption();
      • }
      • }
      • template<class T>
      • class auto_ptr{
      • public:
      • auto_ptr(T *p = 0):ptr(p) {}
      • ~auto_ptr() { delete ptr; }
      • private:
      • T * ptr;
      • };
      • Advantages
        • Resource is deleted automatically whenever object goes out of scope.
        • No resource leaks in exceptional or normal conditions.
      • Problems
        • Cannot be applied for arrays.
      Save ptr to object delete ptr to object