Monday, March 8, 2010

How to prevent memory leak in C plusplus

  1. 'delete' all variables defined by 'new'
    Unless you know what you are doing, you have to delete any variables which are defined by 'new'. so that you free the same memory you allocated.

    char* str = new char [30];
    delete [] str;
  2. Watch those pointer assignments
    Every dynamic variable (allocated memory on the heap) needs to be associated with a pointer. When a dynamic variable becomes disassociated from its pointer(s), it becomes impossible to erase. Again, this results in a memory leak.

    char* str1 = new char [30];
    char* str2 = new char [40];
    strcpy(str1, "Memory leak");
    str2 = str1; // Bad! Now the 40 bytes are impossible to free.
    delete [] str2; // This deletes the 30 bytes.
    delete [] str1; // Possible access violation.
  3. Be careful with local pointers
    A pointer you declare in a function is allocated on the stack, but the dynamic variable it points to is allocated on the heap. If you don't delete it, it will persist after the program exits from the function.

    void Leak(int x){
    char* p = new char [x];
    // delete [] p; // Remove the first comment marking to correct.
    }
  4. Pay attention to the square braces after "delete"
    Use "delete" by itself to free a single object. Use "delete" [] with square brackets to free a heap array. Don't do something like this

    char* one = new char;
    delete [] one; // Wrong
    char* many = new char [30];
    delete many; // Wrong!


No comments:

Post a Comment