[C + +] memory space layout, new/delete, malloc/free

Posted by joliocesar on Mon, 24 Jan 2022 01:52:56 +0100

Layout of memory space

Each application has its own independent memory space, which generally has the following areas

  • Stack space

    Every time a function is called, a continuous stack space will be automatically allocated to store the local variables generated by the function, which will be automatically recycled after the function is called

    Automatic distribution and recycling

  • Heap space

    You need to take the initiative to apply for and release

    • In the process of program running, in order to freely control the life cycle and size of memory, the memory of heap space will often be used

      (apply when you need it, and release it manually when you don't need it

      • malloc \ free

        Enter the required number of bytes. If the application for heap space memory is successful, the address of the first byte will be returned.

        int *p = (int *) malloc(4);
        // The type depends on what will be done with this address 
        *p = 10;
        // Use the allocated 4 bytes to store 10 bytes
        free(p);
        

        After use, the address is passed in to free memory

        You can release as many bytes as you want. You can't release only part of the bytes.

        If char type

        char *p = (char *) malloc(4);
        *p = 10; 
        // 10 is placed only in the first byte of the allocated byte
        *(p + 1) = 20;
        // Give next byte
        // Equivalent to
        p[0] = 10;
        p[1] = 20;
        free(p);
        

        Note: pointer variable p is stored in stack space


        (X86 environment is 32bit, so it takes up 4 bytes, and if it is 64 bit environment, it takes up 8 bytes

        The pointer variable p of stack space points to the contents of heap space

        What disappears after the function call is the content of stack space, and the content of heap space will not disappear, so the applied space should be released before the function call is completed.

      • new \ delete

        As long as you see new, you apply for memory from the heap space

        int *p = new int;
        // Request four bytes
        
        *p = 10;
        delete p;
        char *p = new char; 
        // Request a byte
        
        *p = 10;
        delete p;
        // Release a byte
        // If you want to request four bytes
        char *p = new char[4];
        delete[] p;
        // If new uses brackets, delete also needs brackets
        // Without brackets, it is equivalent to releasing only one byte
        

        be careful! Different uses of new!

        int *p0 = new int;
        // No initialization value;
        int *p1 = new int();	
        // Initialize to 0;
        int *p2 = new int(5);	
        // Initialize to 5;
        int *p3 = new int[3];	
        // Array element is not initialized;
        int *p4 = new int[3](); 
        // All 3 array elements are initialized to 0;
        int *p5 = new int[3]{}; 
        // All 3 array elements are initialized to 0;
        int *p6 = new int[3]{5};
        // The first element of the array is initialized to 5, and other elements are initialized to 0;
        
    • After the heap space application is successful, the address of that memory space will be returned

    • The application and release must be one-to-one, or memory leakage will occur

      • Comparison between new and malloc

        1. Bad will be thrown when new memory allocation fails_ Alloc exception, NULL will not be returned; malloc returns NULL when it fails to allocate memory
        2. When applying for memory allocation with the new operator, there is no need to specify the size of the memory block; malloc needs to explicitly indicate the size of memory required
        3. operator new and operator delete can be overloaded, but malloc and free cannot be overloaded
        4. new/delete will call the constructor / destructor of the object to complete the construction / destructor of the object; And malloc won't
        5. malloc and free are standard library functions of C++/C language; new/delete is a C + + operator
        6. The new operator dynamically allocates memory space for objects from free storage, while the malloc function dynamically allocates memory from the heap.

    memset()

    It is a faster method to clear the memory of large data structures (such as objects, arrays, etc.).

    void * memset( void *_Dst, int _Val, size _t_Size )

    From_ Dst start, continuous_ t_Size bytes, and the value of each byte is set to_ Val.

    int *p = (int *) malloc(sizeof(int) * 10);
    *p = 0; 
    // Just initializing the first four bytes to 0 does not clear them all
    // memset should be used
    memset(p, 0, sizeof(int) * 10);
    // Object reset
    Person person;
    person.m_id = 1;
    person.m_age = 10;
    person.m_height = 100;
    memset(&person,0,sizeof(person));
    Person persons[] = {{2,5,67}, {4,6,23}, {7,3,54}};
    memset(&person,0,sizeof(persons));
    
  • Code area (code snippet)

    Unified storage of functions and all codes

    It is read-only and cannot be modified

  • Data segment (global area)

    Used to store global variables, etc

    The whole program exists when running and will not be released automatically

Object memory can exist in three places

  1. Global area (data segment): global variable
  2. Stack space: local variables in functions
  3. Heap space: dynamically request memory (malloc, new, etc.)
// Global area
Person g_person;
int main() {
    // Stack space    
    Person person;
    // Heap space    
    Person *p = new Person;
    return 0;
}

Topics: C++