Common dynamic memory allocation malloc()/free(), new/delete usage and common errors

1. Several ways of dynamic memory allocation
① Allocate memory from the static storage area, the memory has been allocated at compile time, and this memory exists during the entire program running, such as global variables
② Allocate memory from the stack, and the function body ends When the stack memory is automatically destroyed, such as local variables
③ Open up memory from the heap, such as malloc()/new
2. How to use malloc() and free()
malloc()/free() is used to dynamically allocate memory. How to use as follows:

void *malloc(size_t  size);//动态一块开辟size字节大小的内存
void free(void* ptr);               //释放ptr指向的一块内存空间

Example to illustrate the use of malloc()/free()

int *p=(int*) malloc(100);    //指针p指向一个内存空间为100个字节的地址
int *p=(int*) malloc(25*sizeof(int));    //指针p指向25个整型的空间

Since the return value type of malloc() is void*, the corresponding type conversion should be performed before the function.
In addition , there are two memory allocation functions calloc() and realloc(). Their function prototypes are as follows:

void* calloc(size_t num,size_t size);//在内存的动态存储区分配N块长度为size字节的内存,并初始化为0
void* realloc (void* ptr, size_t size);     //将ptr的内存大小增大到size,增加的内存没有进行初始化

Examples of the use of calloc() and realloc() are as follows:

int  *p = (int*) calloc (i,sizeof(int));
int *p = (int*) realloc (numbers, count * sizeof(int));

The main differences between malloc() and calloc() are: calloc will first initialize the memory to 0 before returning a pointer to the memory; the parameters of calloc() contain the number of required elements and the number of bytes contained in each element
realloc() is used to modify the size of the previously allocated memory block, which can expand and shrink the size of the pre-allocated memory block. If you want to expand the memory, the original memory size remains unchanged, and a new memory block is added directly at the end of the original memory block without initialization; if the original memory block cannot be expanded, a new memory block is opened and the original memory block is copied. If you want to shrink the memory, you can directly delete it at the end of the original memory block.
3. How to use new and delete
new/delete dynamic management object
new[]/delete[] dynamic management object array
The following example illustrates the use of new/delete:

int *p1=new int;   //动态分配4个字(一个整型)节的空间单个数据
int *p2=new int(3); //动态分配4个字(一个整型)节的空间并初始化为3
int  *p3=new  int[3];    //调用operator new动态分配12个字节(3个int)的空间,调用了3次构造函数,operator new相当                                         于malloc

delete p1;
delete p2;
delete[] p2;                //调用3次析构函数

malloc()/free(), new/delete, new[]/delete[] must remember to match and use! Otherwise, it will leak memory or even crash
new/delete, and the bottom layer of new[]/delete[] calls
new/delete:
write picture description here
new[]/delete[]
write picture description here
4. The difference between malloc()/free() and new/delete
With malloc( )/free(), why use new/delete, what is the difference between the two? Both
malloc()/free() and new/delete can be used to apply and release dynamic memory. However, for objects of non-static internal data types, the destructor should be automatically executed before the object dies. Since malloc/free is a library function, not an operator, it is not within the control of the compiler to execute the constructor and The task of the destructor is imposed on malloc()/free(), so only new/delete operators can be used.
Difference: ①new is to construct an object and call the constructor to initialize the object. In fact, all operations of new are divided into two steps: apply for memory; call the constructor. When calling delete, first call the destructor, and then destroy the heap memory
② malloc()/free() C/C++ standard library function, new/delete is a C++ operator
③ new/delete supports overloading, and after overloading, it becomes function.
④The internal implementation of new/delete also calls malloc()/free() in essence.
⑤malloc()/free() needs to manually calculate the type size and return a void* pointer. New/delete can calculate the type size by itself and return the pointer of the corresponding type
⑥ If malloc() fails to apply for memory, it will return a null pointer, and if new fails to apply for memory , a bad_alloc exception will be thrown or a null pointer will be returned
. There are some out-of-bounds accesses of memory, which cause some information involved in the malloc() allocation function to be destroyed. The next time you use malloc() to apply for memory, malloc() will fail and return NULL 6. The dynamic memory transfer problem is defined in the function body When the temporary variable function ends, the memory on the stack will be automatically destroyed. If you want to return the variable, you can open up a new memory on the heap



void GetMemory(char *p,int mum)
{
   p=(char*)malloc(sizeof(char)*num);
}
int main()
{
   char *str=NULL;
   GetMemory(str,10);
   strcpy(str,"hello");
}

There are two serious problems in this program:
①p is essentially a temporary backup of str. Although p has applied for heap memory, str is still NULL when the main() function is returned. When the strcpy() function is executed, the program will Crash
② The address in the heap cannot be obtained when returning from the Memory() function, and the memory cannot be used continuously or released, so calling the Memory() function once will generate a memory leak of mun bytes.
Solve above There are three ways to solve the memory leak problem:
①In C language, use a pointer to a pointer to solve this problem, and pass the address of str to the function GetMemory()
②In C++, pass a reference to the str pointer ③Use the
return value to pass the memory

void GetMemary1(char **p,int num)
{
  *p=(char*)malloc(sizeof(char)*num);
}
void GetMemary2(char * &p,int num)
{
  p=(char*)malloc(sizeof(char)*num);
}
void *GetMemary3(int num)
{
  char *p=(char*)malloc(sizeof(char)*num);
return p;
}

Guess you like

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