How memory is allocated:
1. Static storage allocation: Global variables, static variables, etc., which have been allocated storage memory at program compile time, have been in existence for the whole period of program running
2. On the stack of the program: local variables of the program, including the program's formal parameters, only exist during the program's operation
3 Allocated on heap heaps: Dynamic memory allocation, malloc or new
Common Memory Errors:
(1) The memory allocation is unsuccessful, but it is used. Remember to determine if the return is null when malloc, or null to indicate that the memory allocation failed dynamically
(2) Memory allocation is successful. Remember to initialize, malloc is done.
Calloc: (Number of elements, element size), calloc initialized to 0 after allocating memory
ReAlloc: (pointer, new size), modify the allocated memory size, expand or shrink, if the expansion will be added later, will not change the original data
malloc: (byte size), does not initialize itself
(3) Memory allocation succeeded, but exceeded the size of allocated memory when accessing
(4) Forget to release the dynamically allocated memory, or just release a portion, so that the function of each call will be lost once memory, memory leaks, the final program crashes
(5) The memory has been left out, but the pointer is not pointing to null, it becomes a wild pointer, and it is still in use, and unpredictable circumstances can occur.
How the pointer's arguments are passed
(1) Do not use the parameters of the function as pointers to open up dynamic memory.
Example: void GetMemory (int* ptr)
{ptr= (int*) malloc (sizeof (int) *10);}
Here when the function is called, when the argument is passed in, copy a pointer variable ptr value, give it to him, and then open memory within the function, equivalent to change the value of this argument (that is, address)
There is no change to the formal parameter.
Here you can use a pointer or a reference to a pointer.
The return of the function is not returned by the "in-stack pointer", which means that the memory allocated on the program stack is returned, and when it is returned, the memory is freed, so it makes no sense.
Memory management (high-quality programming language C + + 16th Chapter notes)