Memory Errors and leaks in C ++

Source: Internet
Author: User
Translator: fanyamin (http://blog.sina.com.cn/fanyamin)
Translated from the original yolinux turorial, some http://www.yolinux.com/TUTORIALS/C++MemoryCorruptionAndMemoryLeaks.html
Memory Error Type

For programmers, there are two types of memory that can be accessed in Linux. virtual storage space where the user program runs 2. the most common memory error in register memory is the "segmentation violation" error. This is a warning message about the location where memory errors are generated. You can use GDB to locate the error. below are some of the less obvious Error Memory Errors

  • Heap memory error heap memory errors:

    • Try to release free memory that has been released
    • Free memory not allocated
    • Try to write memory that has been released free
    • Try to write unallocated memory
    • Memory Allocation Error
    • Dynamic Array allocation for read/write operations out of bounds
  • Stack memory error (local variable)

    • Read/write static array out of bounds (array index overflow, index greater than array length or negative value)
    • Function pointer corruption: Invalid function pointers are passed and called incorrectly.
Memory leakage

Definition: memory allocation is not released, which results in memory consumption by an application, reduces the available memory of other applications, and eventually causes the system to swap virtual memory with the hard disk, it slows down or crashes when the application reaches the memory resource limit. this may also cause the system to stop working.

  • Many C-library functions allocate malloc memory which must be free, such as strdup

...

Char * oldstring = "Old string ";

Char newstrig = strdup (oldstring );

If (newstring = enomem)... // fail !!!!

...

Free (newstring)

...

Note that C ++'s delete cannot be used, but free must be used.

  • The free memory allocated with malloc must be released.

Char * textstring = malloc (128 * sizeof (char ));

If (textstring = enomem)... // fail !!!!

...

Free (textstring); // don't free if allocation failed

Note: Check for memory allocation errors. Do not release unallocated memory.

  • You must delete the memory that has been created for new in the delete operation.

PTR = new classtypea;

...

Delete classtypea;

  • Inheritance, polymorphism, and error Deletion

Baseclass * obj_ptr = new derivedclass; // allowed due to polymorphism ....

Delete obj_ptr; // This will call the Destructor ~ Parent () and not ~ Child ()

Note: It is necessary to declare the destructor of the base class as a virtual function. Pay attention to the possibility of Memory leakage during forced type conversion, using the cast Conversion Function of C ++ can prevent such errors. compilation will warn you

  • Pointer re-assignment error causes pointer Suspension

If a pointer is assigned a new value before it is released, the hanging pointer and Memory leakage will occur.

Char * A = malloc (128 * sizeof (char ));

Char * B = malloc (128 * sizeof (char ));

B =;

Free ();

Free (B); // will not free the pointer to the original allocated memory.

  • The default copy constructor may not give the correct result.

Copy the constructor to copy and allocate memory. if you need to check and delete the destructor. the value transfer class calls the copy constructor to allocate memory. note: When processing pointers, the default copy constructor may not give the desired result, and it does not know how to copy the content pointed to by the pointer. defining an empty value assignment operator prohibits the use of the default copy constructor.

   ClassA& operator=(const ClassA& right_hand_side);

Good practice: Check with assertions before using and deleting pointers

   assert(ptr !=0)
Memory Corruption uption

Definition: changes or changes the pointer to a specific area in the memory if the memory is not explicitly allocated due to unintentional negligence.

  • Buffer Overflow

Example 1. overwrite the allocated memory

 char *a = malloc(128*sizeof(char));
memcpy(a, data, dataLen); // Error if dataLen too long.

Example 2: Data Index out of bounds: The data index is greater than the array length or is negative

   ptr = (char *) malloc(strlen(string_A));  // Should be (string_A + 1) to account for null termination.
strcpy(ptr, string_A); // Copies memory from string_A which is one byte longer than its destination ptr

Overflow of one byte

  • Use the address before assigning values to memory allocation.
   struct *ABC_ptr;
x = ABC_ptr->name;

In this example, the memory address is null or random.

  • Use released pointer
   char *a = malloc(128*sizeof(char));
..
..
free(a);
   cout << a << endl;  // This will probably work but dangerous.
   ... Do stuff. Probable overwriting of freed memory.
   cout << a << endl;  // No longer the same contents. Memory overwritten by new stuff.
  • Release/delete memory that has been released/deleted

Release a pointer twice

   char *a = malloc(128*sizeof(char));
free(a);
... Do stuff
free(a); // A check for NULL would indicate nothing.
// This memory space may be reallocated and thus we may be freeing
// memory we do not intend to free or portions of another block of
// memory. The size of the block of memory allocated is often held
// just before the memory block itself..
  • Release memory not dynamically allocated
   struct ABC abc;
struct ABC *abc_ptr = &abc;
...
free(abc_ptr);
  • Incorrect deletion: The delete operation must be consistent with the new operation.

The correct operations are new/delete and new []/Delete [].

   ClassABC *abc_ptr = new ClassABC[100];
...
delete [] abc_ptr;

If "delete abc_ptr" is used, the error occurs. Do not use malloc ()/Free () in the C ++ class. It does not call constructor and destructor, do not mix them with new/Delete. For example, free () cannot release the memory created by new, and delete cannot be used to release the memory allocated by malloc ().

  • Exception error

Release memory that has never been allocated. if you use constructors to allocate memory, but an exeption is thrown before the memory is allocated, the Destructor must know this fact. otherwise, you may release the memory that has never been allocated. conversely, if the Destructor throws an exception, the following steps to release the memory may not be executed. this applies to the Destructor that throw exceptions and their nested destructor in stack calls.

  • Pointer Lifecycle

The function that returns a pointer from the stack will no longer be valid for its caller

   int *get_ii()
{
int ii; // Local stack variable
ii = 2;
return &ii;
}
main()
{
int *ii;
ii = get_ii(); // After this call the stack is given up by the routine
// get_ii() and its values are no longer safe.
     ... Do stuff
.. ii may be corrupt by this point.
}

The same is true for local variables in functions (enclosed by braces ).

  • Incorrect function parameter transfer

The pointer passed as the function parameter may be released incorrectly.

  • Hybrid object base class and derived class

When an object is passed as a function parameter, if you mix the base class and derived class of the object, you need to understand the missing function_a (baseclass baseclass_ptr)

{...}

// Call to function function_a (derivedclass_ptr); // note that much of the information contained

// in the derived class will not be passed into
// the function including virtual destructors.
  • Object copy

Do not use memcpy or any bit-based copy function to copy objects. It will not execute class constructor. Who will do this? Passing an object in the parameter list of va_arg () will result in a single-bit copy and will not call the copy constructor.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.