Classic memory operations Analysis

  • Eliminate dangling pointers
  1. Value of the pointer variable is illegal memory address, thereby forming a field guide
  2. Field pointer is not NULL pointer is pointing to unavailable memory address pointer
  3. NULL pointer no harm, good judgment, and good debugging
  4. C language but can not determine whether the address stored in a pointer legitimate
  • The origin of the wild pointer
  1. Local pointer variable is not initialized (initialize pointers need to define NULL)
  2. Variable pointer is being destroyed before pointer
  3. Use has been released pointer (free)
  4. Was incorrectly cast
  • The basic principle
  1.  Never return address local variables and partial array (because the function will be released after the operation in the stack)
  2. After defining any variable must be initialized to 0
  3. After the array of characters must be confirmed in order to become a string terminator 0
  4. Any use function associated with the memory operations must be specified length information
  • Common memory errors
  1. Uninitialized pointer structure members:
  2. Structure member pointer does not allocate sufficient memory
  3. Memory allocation successful, but uninitialized
  4. Memory cross-border operation
  • Traffic rules memory operations
  1. After the dynamic memory allocation, you should check the pointer immediately, whether the value is NULL, NULL pointer prevent the use of
  2. After the free NULL pointer assignment must immediately
  3. Any operations related to memory operations must tape length information
  4. malloc and free operations operations must match , to prevent memory leaks and release many times, in the main function of malloc should be free in the main, in the malloc function func func should be in the free.
void print(int*p,int size)
{
    int i = 0;
    char buf[128] = {0};
    snprintf(buf,sizeof(buf),"%s","Hello World!");
    for(i=0;i<size;i++)
    {
        printf("%d\n",p[i]);
    }
}
 
summary:
  1. Memory nature of the error pointer from the saved address to an illegal value
  2. Uninitialized pointer variable, the random number stored
  3. Pointer cross-border operation resulted in memory
  4. Memory leaks from malloc and free does not match
  5. Generating a memory leak free when more than the number of malloc
  6. When fewer than malloc free, the program may crash
 
 
 

Guess you like

Origin www.cnblogs.com/chengeputongren/p/12175726.html