gogoWebsite

new free memory understanding c++

Updated to 2 days ago

After freeing memory, the content of the pointer itself will not change, that is, the pointer's pointing has not changed, but the memory area corresponding to the address stored in it is marked as unused in the system and the memory area pointed to has been reclaimed by the system. This piece of memory may be allocated to other processes or variables in processes at any time, so you should avoid using this pointer, so you should set this pointer to NULL. The NULL pointer does not point to any address. nullptr  is the same as NULL

The pointer points to the array with delete[]  (it is OK to have spaces in the middle), otherwise delete

delete[] 
delete [] 

As follows, other pointers point to the first address of this new pointer. Only one need to be released, and one of the two can be released arbitrarily. Both cannot be released because they point to the same piece of memory (the memory block that has been released cannot be released). If other pointers do not point to the first address of this new pointer, they cannot be released with other pointers.

int *cossinidx = new int[ndstwidth * 2];
int * cossinptr = cossinidx;

The temporary variable pointer defined inside the function is like other variables. The end of the function is automatically released, but the memory space of new will not be released, so it must be manually released.

If the pointer to the first address of this new space is defined in the function, the end of the function will be automatically released. Set it to NULL, which is because it is worried that it will be used again in this function. If the new space is released at the end of the function, the pointer can also be not set to NULL.

Each return value after the new space of the function must be released before it

The pointer to the first address of this new pointer can only release this memory because a lot of information is stored in the first address of the address, including memory size and other information. When the pointer is released, the system will automatically release the memory based on this information.

delete[]   rg   Used to free the memory pointed to by rg! ! Also call the destructor of each object in the array one by one

new() allocates a memory space of a size of this type and initializes the variable with the value in parentheses.

new[] allocates n sizes of this type and initializes these variables with the default constructor.

int *pp=new int;//delete pp;
int *p0=new int[3] {1,2,3};//delete[] p0;
int *p1=new int[3] ;//delete[] p1;

malloc is the same as new, but free space with free

 

It is safe to apply delete to a null pointer

 

When a pointer is defined but not assigned, the pointer is NULL

int* p;

 

Example of creating class object new: CTest* pTest = new CTest();

delete pTest;

pTest is used to receive pointers of class objects.