Dynamic Memory Management
Memory Leaks内存溢出
Lose access to memory allocated on the heap.
Easy to lose when dealing with pointers
Managing Memory
Programmer gets memory from the heap
Programmer must free it when done
Commonly referred to as garbage collection.
Good exam question
What are specific scenarios that can result in a memory leak?
Think about the definition of a memory leak as we continue to discuss dynamic memory management.
Strategies to Manage Dynamic Memory
Avoid using dynamic memory.
Balance allocation with deallocation.
news with deletes
Automatic Garbage Collection
While these do exist for C++, tend to be inefficient and slow things down.
RAII – Resource Allocation is Initialization
When possible
allocate in the constructor
deallocate in the destructor
Dynamic Classes
Classes that use dynamic memory, must implement certain functions to effectively manage memory on the heap.
Rule of Three If you implement one of the following, you must implement the other two!
Destructor
Copy Assignment
Copy Constructor
Rule of Five (We won’t cover these)
Move Assignment
Move Constructor
内存泄漏与内存溢出:
内存溢出 out of memory,是指程序在申请内存时,没有足够的内存空间供其使用,出现out of memory;比如申请了一个integer,但给它存了long才能存下的数,那就是内存溢出。
内存溢出就是你要求分配的内存超出了系统能给你的,系统不能满足需求,于是产生溢出。
内存泄漏是指你向系统申请分配内存进行使用(new),可是使用完了以后却不归还(delete),结果你申请到的那块内存你自己也不能再访问(也许你把它的地址给弄丢了),而系统也不能再次将它分配给需要的程序。一个盘子用尽各种方法只能装4个果子,你装了5个,结果掉倒地上不能吃了。这就是溢出!比方说栈,栈满时再做进栈必定产生空间溢出,叫上溢,栈空时再做退栈也产生空间溢出,称为下溢。就是分配的内存不足以放下数据项序列,称为内存溢出.
内存泄漏 memory leak,是指程序在申请内存后,无法释放已申请的内存空间,一次内存泄露危害可以忽略,但内存泄露堆积后果很严重,无论多少内存,迟早会被占光。本意是申请的内存空间没有被正确释放,导致后续程序里这块内存被永远占用(不可达),而且指向这块内存空间的指针不再存在时,这块内存也就永远不可达了,内存空间就这么一点点被蚕食
memory leak会最终会导致out of memory!
泄漏就是内存申请后,用完没有释放,造成可用内存越来越少。
溢出指用户实际的数据长度超过了申请的内存空间大小,导致覆盖了其他正常数据,容易造成程序异常,严重的,攻击者可以以此获取程序控制权。
Last updated
Was this helpful?