1 / 25

Dynamic memory allocation

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.

kareem
Download Presentation

Dynamic memory allocation

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Dynamic memory allocation Huang Alex

  2. 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

  3. Roadmap • General memory management conception and topic: • Memory allocation methods • Major faults and associated strategy • Other topics • Senior resource management items used in C++

  4. 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 function’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!

  5. 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.

  6. 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.

  7. 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对象所占的堆空间。 }

  8. Stack storage • To prohibit the class to be the base, we can declare the destruction as protected or private.

  9. 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 ; //防止使用悬挂指针

  10. Roadmap • General memory management conception and topic: • Memory allocation methods • Major faults and associated strategy • Other topics • Senior resource management items used in C++

  11. 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 initialized. • Strategy: never forget initializing the array or variables once you declare them. • Fault: memory allocation succeed and initialized but it has exceed 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.

  12. 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!

  13. Roadmap • General memory management conception and topic: • Memory allocation methods • Major faults and associated strategy • Other topics • Senior resource management items used in C++

  14. 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;

  15. roadmap • General memory management conception and topic: • Memory allocation methods • Major faults and associated strategy • Other topics • Senior resource management items used in C++

  16. Senior resource management items used in C++ • Use objects to manage resources. • Think carefully about copying behavior in resource-managing classes. • Provide access to raw resources in resource managing classes. • Use the same form in corresponding use of new and delete. • Store newed objects in smart pointers in standalone statements.

  17. 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.

  18. 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 object (smart pointer) whose destructor will automatically calls delete on what it points to.

  19. 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.)

  20. 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.

  21. Senior resource management items used in C++ • Use objects to manage resources. • Think carefully about copying behavior in resource-managing classes. • Provide access to raw resources in resource managing classes. • Use the same form in corresponding use of new and delete. • Store newed objects in smart pointers in standalone statements.

  22. Senior resource management items used in C++ • Use objects to manage resources. • Think carefully about copying behavior in resource-managing classes. • Provide access to raw resources in resource managing classes. • Use the same form in corresponding use of new and delete. • Store newed objects in smart pointers in standalone statements.

  23. 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

  24. 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;

  25. Detection of memory leak • http://www-128.ibm.com/developerworks/cn/linux/l-mleak2/index.html

More Related