C + + memory management
What is memory management?
Thinking: What is the nature of memory? ----> Resources
Thinking: Who is in charge of memory resources? ----> Operating Systems
Thinking: What can we do? ----> Application/Return
Application / Returning memory resources is memory management
How do I request and release memory in C + +?
Apply ---> Use operator new
Release ---> Use operator Delete
That
Request Memory: int *p = new int;
Free Memory: delete p;
This will apply and release a memory or some type of memory
Thinking: How to apply and release block memory?
int *arr = new INT[10]; Block memory of 10 integer types applied
delete []arr; Freeing block memory
Think: is the application of memory must be able to apply for success? Obviously, not necessarily!!
Therefore, when encoding, it is necessary to process the possible application memory failure
int *p = new int[1000];
if (NULL = = p)
{
Memory allocation failure
}
After releasing the memory, assign a value of NULL to the corresponding pointer, i.e.
Delete p; delete []p;
p = NULL; p = NULL;
If the free pointer pail is empty, then the current pointer is still pointing to the corresponding block of memory, if we accidentally call the delete again, then the same piece of memory will be recycled, once recycled, the computer will be an exception.
Summary:
1) Use new to request memory, use Delete to free memory
2) When requesting memory, you need to determine if the application is successful, and you need to set the pointer to empty after releasing the memory
3) New and delete to use
Last look at an example:
In the heap, request 100 char types of memory, copy the Hello Imooc string into memory in the allocated heap, print the string, and finally free up memory.
Full executable program:
#include <string.h>#include<iostream>using namespacestd;intMainvoid){ Char*str =New Char[ -];//Request 100 char types of memory in a heapstrcpy (str,"Hello Imooc");//Copy the Hello C + + string into memory in the allocated heapcout<<str<<endl;//Print a string Delete[]str;//Freeing MemoryStr=NULL; return 0;}
Vernacular C + + series (5)