Five memory storage areas of C++, new/delete of C++, malloc/free of C

In C++, the memory is divided into 5 areas in detail

  1. Stack
    Function 局部变量storage area, automatically allocated and released by the system

  2. Heap
    Programmers dynamically apply for memory, newcome out of memory, or come out of malloc. Use delete and free to release manually to prevent overflow

  3. Global/static storage area
    Global variables and static static variable storage area

  4. Constant storage area
    such as constant string, etc. "I am Chinese"

  5. Program code area
    The area where the program is stored

C++ application for dynamic memory is new/delete, which is easier to use than C's malloc/free. It is essentially a method of calling C, but there are more initializations, etc.

  1. new/delete
    new not only allocates memory, but also does some initialization work, and delete also does some additional cleanup work.
    For example, the pointer of a new class will call the constructor of this class to perform initialization work.

    int *p1 = new int //单个变量指针
    int *p2 = new int(10); //顺带初始化了
    int *p3 = new int[10]  //申请一个数组,指针指向它
    delete p1;
    delete p2;
    delete [] p3;
    
  2. malloc/free
    If the application fails, return NULL. Try not to use it when writing C++ programs, just use new/delete

    //很笨,只会申请一个大小为**的内存,返回是空指针,不知道指向谁,还要强制类型转换成(int*)
    int *p1 = (int*)malloc(sizeof(int));
    int *p2 = (int*)malloc(10*sizeof(int));
    //释放的时候倒是简单,不管数组还是单个变量,不用加[]
    //!!!!!!!注意是个free函数,不是  free p1;
    free(p1);
    free(p2);
    

Guess you like

Origin blog.csdn.net/qq_41253960/article/details/124390587