C Language heap memory management problems, memory leaks, use of wild pointers, illegal release pointers
(1) The Open memory is not released, causing a memory leak
(2) Wild hands are used or released
(3) Illegal release of hands
(1) The Open memory is not released. A memory leak, the following sample can cause a 20-byte leak, a memory leak is not an error that will immediately cause a failure, but
It consumes the system memory.
void Function1 () {char *pa;pa = (char*) malloc (sizeof (char) *20), if (NULL!=pa) {strcpy (PA, "Hello");p rintf ("PA =%x\n", ( unsigned int) pa);p rintf ("PA =%s\s", PA);} return;}
(2) Wild hands are used or released
The wild pointer is a memory pointer that has been freed, and the position he points to has been freed using the free or realloc function, but the pointer is still in use.
void Function2 () {char *pa;pa = (char*) malloc (sizeof (char) *20), if (NULL!=pa) {strcpy (PA, "Hello");p rintf ("PA =%x\n", ( unsigned int) pa);p rintf ("PA =%s\s", PA);} Free (PA);p rintf ("Pa =%s", PA); return;}
The correct memory release should be the following
void Function2 () {char *pa;pa = (char*) malloc (sizeof (char) *20), if (NULL!=pa) {strcpy (PA, "Hello");p rintf ("PA =%x\n", ( unsigned int) pa);p rintf ("PA =%s\s", PA);} Free (PA);p a = null;if (NULL! = PA) {printf ("Pa =%s\n", (unsigned int) PA);} return;}
(3) Illegal release of hands
void Function3 () {char a[20];int b;free (a); free (&b); return;}
In the above program, A[20] is an array on a stack. A is the address of this memory; B is a variable above the stack. The &b is its address. The memory on these stacks, the compiler
It is a mistake to use free to dispose of resources by proactively managing and reclaiming them.
Char *pa;pa = (char*) malloc (sizeof (char) *20), Free (PA), Free (PA);
The procedure above. Releasing memory two times is an incorrect notation, because after the first release, the address has become, unallocated heap memory. The free function does not release unallocated heap memory.
char *pa;char *pa;pa = (char*) malloc (sizeof (char) *20);p B = Pa++;free (PB);
In the above program, although PA is a allocated heap memory pointer, PB as the PA address plus 1, is also a heap memory pointer, and this pointer is also the allocated memory. However, memory PB is still an illegal memory release. This is because the pointer is not allocated from malloc. But a pointer value in the middle.
C Language heap memory management problems, memory leaks, use of wild pointers, illegal release pointers