An introduction to C++ dynamic memory allocation

  • 2020-06-12 10:06:25
  • OfStack

introduce

There is a memory manager in the operating system (Memory Manager), or MM for short, which manages memory.

Services provided by MM: An application can request a specified amount of memory from MM (borrowed) and should release (return) it when it is used up.

Such as:


void* p = malloc(1024);// To apply for, MMM Out of memory 
free(p); // Release, return MM

1. The memory area managed by MM becomes the heap (Heap).

2. As long as malloc is used, MM will lend out. If the application is not returned, MM will not ask you for free. If an application keeps malloc instead of free, it will eventually run out of MM memory.

When MM has no more spare memory, malloc returns NULL to indicate that it has run out of memory.

malloc function


void* malloc(int size)
       parameter size : Specifies the amount of memory space to request 
       The return value: void* , point to it 1 Block memory address. (MM It doesn't care what kind of data you're storing in this piece of memory, so return void*)

free function


void free(void* ptr)
      parameter ptr:  previous malloc The memory address returned 
      The return value : void*  , point to it 1 Block memory address 

Using an example


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
class Object
{
public:
 int a;
 int b;
 char name[32];
};
int main()
{
 // Request heap memory 
 Object *object = (Object *)malloc(sizeof(Object));
 // To store data 
 object->a = 1;
 object->b = 5;
 strcpy(object->name, "wpf");
 // Free memory 
 free(object);
 object = NULL; // Good programming style 
 return 1;
}

conclusion


Related articles: