C++(5) - Memory Management

Ordinary memory allocation and release:

  • Allocate memory: int *p = new int;
  • Free memory: delete p;
  • new and delete should be used together to prevent the requested memory from being deleted and emptied in time.

How to allocate and free block memory:

  • int *arr = new int[10]; //Apply for block memory
  • delete []arr; // release block memory

Check whether the request for memory is successful:

int *p = new int[1000]; if(NULL == p){//Memory allocation failed}

Let me say one more thing here, why do you write "NULL == p" instead of "p == NULL"? This is the experience in the actual development process, which can prevent yourself from making mistakes and writing the code as "p = NULL" such assignments statement. It can be said to be very clever!

Notes on freeing memory: (be sure to set the pointer to null)

After using "delete p;", you need to write one more statement: p = NULL ;//If there is no such statement, the pointer still only wants the original memory address.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324765689&siteId=291194637