Dynamic memory allocation

25
Dynamic memory Dynamic memory allocation allocation Huang Alex Huang Alex

description

Dynamic memory allocation. Huang Alex. Agenda. General memory management conception and topic: Memory allocation methods Major faults and associated strategy Other topics Senior resource management items used in C++ Detection and catch of memory leak. Roadmap. - PowerPoint PPT Presentation

Transcript of Dynamic memory allocation

Dynamic memory Dynamic memory allocationallocation

Dynamic memory Dynamic memory allocationallocation

Huang AlexHuang Alex

Agenda• General memory management

conception and topic:– Memory allocation methods– Major faults and associated strategy– Other topics

• Senior resource management items used in C++

• Detection and catch of memory leak

Roadmap• General memory management conce

ption and topic:– Memory allocation methods– Major faults and associated strategy– Other topics

• Senior resource management items used in C++

Allocation methods• Static storage

– Memory will be allocated during compile period and it will exist during the running period. For example, global and static variables.

• Stack storage– Memory will be allocated during running period for func

tion’s internal variables and be freed after function finish its task. Stack operations are located in the CPU’s instruction set and it has highly efficiency but limited.

• Heap storage– Memory will be allocated when programmer using new/

malloc() and the life circle of the heap is determined by programmer itself. Heap variable can be returned in a function but stack variable can’t!

Static storage• class Base

{  public:   static Type s_object ;}class Derived1 : public Base / / 公共继承{  … … // other data }class Derived2 : public Base / / 公共继承{  … … // other data }

Base example ;Derivde1 example1 ;Derivde2 example2 ;example.s_object = …… ;example1.s_object = …… ; example2.s_object = …… ;

• Notes: all the instance dervied1/dervied2/base will use one copy of s_object.

Ban gen heap storage• Ban generating heap object:

– #include <stdlib.h> // 需要用到 C 式内存分配函数 class Resource ; // 代表需要被封装的资源类 class NoHashObject {   private:    Resource* ptr ;// 指向被封装的资源    ... ... // 其它数据成员    void* operator new(size_t size) // 非严格实现,仅作示意之用    {     return malloc(size) ;    }    void operator delete(void* pp) // 非严格实现,仅作示意之用    {     free(pp) ;    }   public:    NoHashObject()    {     // 此处可以获得需要封装的资源,并让 ptr 指针指向该资源     ptr = new Resource() ;    }    ~NoHashObject()    {     delete ptr ; // 释放封装的资源    } };

– Notes: declare the new/delete as private will forbidden the generation of heap variable.

Heap storage (force gen heap)

• void main(void) {   char* temp = new char[sizeof(NoHashObject)] ;

  // 强制类型转换,现在 ptr 是一个指向 NoHashObject 对象的指针   NoHashObject* obj_ptr = (NoHashObject*)temp ;

  temp = NULL ; // 防止通过 temp 指针修改 NoHashObject 对象

  // 再一次强制类型转换,让 rp 指针指向堆中 NoHashObject 对象的 ptr 成员   Resource* rp = (Resource*)obj_ptr ;

  // 初始化 obj_ptr 指向的 NoHashObject 对象的 ptr 成员   rp = new Resource() ;   // 现在可以通过使用 obj_ptr 指针使用堆中的 NoHashObject 对象成员了   ... ...

  delete rp ;// 释放资源   temp = (char*)obj_ptr ;   obj_ptr = NULL ;// 防止悬挂指针产生   delete [] temp ;// 释放 NoHashObject 对象所占的堆空间。 }

Stack storage• To prohibit the class to be the

base, we can declare the destruction as protected or private.

Ban gen stack object (singleton pattern)

• class NoStackObject {   protected:    NoStackObject() { }    ~NoStackObject() { }   public:    static NoStackObject* creatInstance()    {     return new NoStackObject() ;// 调用保护的构造函数    }    void destroy()    {     delete this ;// 调用保护的析构函数    } };

• NoStackObject* hash_ptr = NoStackObject::creatInstance() ; ... ... // 对 hash_ptr 指向的对象进行操作 hash_ptr->destroy() ; hash_ptr = NULL ; // 防止使用悬挂指针

Roadmap • General memory management conce

ption and topic:– Memory allocation methods– Major faults and associated strategy– Other topics

• Senior resource management items used in C++

Major faults and associated strategies

• Fault: The memory allocation is failure but it is employed.• Strategy: it should check the validation before using it. Such

as if (p == NULL)• Fault: memory allocation succeed but it hasn’t been initiali

zed.• Strategy: never forget initializing the array or variables once

you declare them.• Fault: memory allocation succeed and initialized but it has e

xceed the boundary of the memory (array).• Strategy: strictly check the suffix of the array for not adding

1 or subtract 1.• Fault: forget to free the memory that lead to memory leak.• Strategy: new/delete and malloc/free must be pair.

Major faults and associated strategies

• Fault: free the memory but still use it. It has 3 conditions:– 1. calling relationship is too complicated and it is

hard to clear whether it has free the memory. – Strategy: redesign the data structure.– 2. return the pointer or reference to stack memory– Strategy: you can only return heap memory.– 3. it hasn’t set the pointer as NULL even after

delete/free the memory.– Strategy: set the pointer as NULL!

Roadmap• General memory management conce

ption and topic:– Memory allocation methods– Major faults and associated strategy– Other topics

• Senior resource management items used in C++

Comparison of array and pointer

• Example:– char a[] = “hello”;

a[0] = ‘X’;cout << a << endl;char *p = “world”; // p is point to const stringp[0] = ‘X’; // compile can’t find the fault but in running time.cout << p << endl;

roadmap• General memory management

conception and topic:– Memory allocation methods– Major faults and associated strategy– Other topics

• Senior resource management items used in C++

Senior resource management items used in C++

• Use objects to manage resources.• Think carefully about copying behavior in resourc

e-managing classes.• Provide access to raw resources in resource mana

ging classes.• Use the same form in corresponding use of new an

d delete.• Store newed objects in smart pointers in standalo

ne statements.

Use objects to manage resources

• Topic involved:– class Investment { ... }; – Investment* createInvestment(); – void f() – { – Investment *pInv = createInvestment(); // 调用工厂函数 – ... // 使用 pInv – delete pInv; // 释放该对象 – } – There are something will invoke failure:– 1. if there is a premature return somewhere in the ‘…’.– 2. if there is exception in the ‘…’.– 3. if createInvestment() and delete were in a loop.

Use objects to manage resources

• improved solution:– void f()– {

• std::auto_ptr<Investment>pInv(createInvestment());• …

– }– The function of auto_ptr: it is a pointer –like obj

ect (smart pointer) whose destructor will automatically calls delete on what it points to.

Use objects to manage resources

• Two critical aspects of using objects to manage resources:– Resources are acquired and immediately

turned over to resource-managing objects.– Resource-managing objects use their

destructors to ensure that resources are released.

• reference-counting smart pointer:– Tracks the count of point to the specific resources and it will

automatically delete the resource while there is no pointer point to the resource. Notes: it can’t break loop reference (example, the two objects that hasn’t point to the other user.)

Use objects to manage resources (things to

remember)– In one word, this topic instruct programmer

to use smart pointer (auto_ptr or shared_ptr) to be manage resource object as possible to avoid resource leak.

– Two commonly useful RAII class are tr1::shared_ptr and auto_ptr.tr1::shared_ptr is usually the better choice, as its behavior when copoied to intuitive. Copying an auto_ptr sets it to null.

Senior resource management items used in

C++• Use objects to manage resources.• Think carefully about copying behavior in resou

rce-managing classes.• Provide access to raw resources in resource mana

ging classes.• Use the same form in corresponding use of new an

d delete.• Store newed objects in smart pointers in standalo

ne statements.

Senior resource management items used in

C++• Use objects to manage resources.• Think carefully about copying behavior in resourc

e-managing classes.• Provide access to raw resources in resource mana

ging classes.• Use the same form in corresponding use of new

and delete.• Store newed objects in smart pointers in standalo

ne statements.

New/delete should be the same form

• Example:– string *stringptr1 = new string; string

*stringptr2 = new string[100]; ... delete stringptr1;//

delete stringptr1 delete [] stringptr2;// delete stringptr2

New/delete should be the same form especially for typedef

• Example:– typedef std::string AddressLines[4];

std::string *pal = new AddressLines;delete pal;

delete [] pal;

Detection of memory leak

• http://www-128.ibm.com/developerworks/cn/linux/l-mleak2/index.html