dynamic memory allocation n.
Download
Skip this Video
Loading SlideShow in 5 Seconds..
Dynamic memory allocation PowerPoint Presentation
Download Presentation
Dynamic memory allocation

Loading in 2 Seconds...

play fullscreen
1 / 25

Dynamic memory allocation - PowerPoint PPT Presentation


  • 311 Views
  • Uploaded on

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.

loader
I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
capcha
Download Presentation

PowerPoint Slideshow about 'Dynamic memory allocation' - kareem


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.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
agenda
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
Roadmap
  • General memory management conception and topic:
    • Memory allocation methods
    • Major faults and associated strategy
    • Other topics
  • Senior resource management items used in C++
allocation methods
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!
static storage
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 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
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
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
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 ; //防止使用悬挂指针
roadmap1
Roadmap
  • General memory management conception and topic:
    • Memory allocation methods
    • Major faults and associated strategy
    • Other topics
  • Senior resource management items used in C++
major faults and associated strategies
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.
major faults and associated strategies1
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!
roadmap2
Roadmap
  • General memory management conception and topic:
    • Memory allocation methods
    • Major faults and associated strategy
    • Other topics
  • Senior resource management items used in C++
comparison of array and pointer
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;
roadmap3
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
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.
use objects to manage resources
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 resources1
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.
use objects to manage resources2
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
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 c1
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.
senior resource management items used in c2
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.
new delete should be the same form
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
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
Detection of memory leak
  • http://www-128.ibm.com/developerworks/cn/linux/l-mleak2/index.html