How to monitor memory leaks

Source: Internet
Author: User
Tags int size sprintf
 turn from: http://zhidao.baidu.com/question/176936319.html 
First, we checked the code and found that all the code was allocating memory with new, with Delete to free the memory. So, can we replace all the new and delete operators with a full replacement? No. Because the size of the code is too large, there is no other benefit than wasting time. The good news is that our source code is written in C + +, so this means there's no need to replace all new and delete, but overload the two operators. Yes, the value is overloaded with these two operators, so we can do something before allocating and freeing the memory. This is an absolute good news. We also know how to do it. Because, MFC also do so. What we need to do is keep track of all memory allocations and interaction references and memory release. Our source code is written in Visual C + +, and of course this solution can be easily used in other C + + code. The first thing to do is to overload the new and delete operators, which will be used in all the code. 
                                         In stdafx.h, we add: #ifdef _debug inline void * __cdecl operator new (unsigned int size,

      const char *file, int line) {};
      inline void __cdecl operator delete (void *p) {}; #endif this way, we overload the new and delete operators. We use $ifdef and #endif to wrap these two overloaded operators so that the two operators do not appear in the release version. Looking at this code, you will find that the new operator has three parameters, which are the allocated memory size, the file name that appears, and the line number. This is necessary and important for finding a memory leak. Otherwise, it will take a lot of time to find out exactly where they appear. Adding this code, our code for calling new () is still pointing to the new operator that accepts only one parameter, not the operator that accepts three arguments. In addition, we do not want to record all the new operator statements to include __file__ and __line__ parameters. What we need to do is automatically let all the new operators that accept a parameter invoke the new operator that accepts three arguments. This can be done with a little bit of skill, such as the following macro definition, #ifdef _DEBUG #define DebuG_new New (__file__, __line__) #else #define DEBUG_NEW New #endif #define NEW debug_new Now all we have accepted The new operator of a parameter becomes the new operation symbol that accepts three parameters, and __file__ and __line__ are automatically inserted into it by the precompiled compiler. Then, the actual tracking is done. We need to add some routines to our overloaded functions so that they can do the work of allocating memory and freeing up memory.
                                         To do so, #ifdef _debug inline void * __cdecl operator new (unsigned int size,
const char *file, int line) {void *ptr = (void *) malloc (size);
Addtrack ((DWORD) PTR, size, file, line);
      return (PTR);
      };
      inline void __cdecl operator delete (void *p) {removetrack ((DWORD) p); free (p);
      }; #endif In addition, you need to overload the new[] and delete[] operators in the same way.
They are omitted here. Finally, we need to provide a set of functions Addtrack () and Removetrack ().
I use STL to maintain the connection table of the storage memory allocation record.
The two functions are as follows: typedef struct {DWORD address;
DWORD size;
Char file[64];
      DWORD Line;

      } Alloc_info;

      typedef list<alloc_info*> Alloclist;

      Alloclist *alloclist;

void Addtrack (DWORD addr, DWORD asize, const char *fname, DWORD lnum) {Alloc_info *info; IF (!alloclist) {alloclist = new (alloclist);}
info = new (alloc_info);
info->address = addr;
strncpy (Info->file, fname, 63);
Info->line = Lnum;
Info->size = asize;
      Alloclist->insert (Alloclist->begin (), info);

      };

void Removetrack (DWORD addr) {alloclist::iterator i;
if (!alloclist) return; 
for (i = Alloclist->begin (); I!= alloclist->end (); i++) {if ((*i)->address = = addr) {Alloclist->remove ((*i));
Break
  }
}
      }; Now, before our program exits, Alloclist stores memory allocations that are not freed. In order to see what they are and where they are assigned, we need to print out the data in the alloclist.
      I used the output window in Visual C + + to do this.
void Dumpunfreed () {alloclist::iterator i;
DWORD totalsize = 0;

Char buf[1024];

if (!alloclist) return; for (i = Alloclist->begin (); I!= alloclist->end (); i++) {sprintf (buf, "%-50s:line%d, address%d%d unfreed", *i
)->file, (*i)->line, (*i)->address, (*i)->size);
OutputDebugString (BUF);
TotalSize + = (*i)->size; sprintf (buf, "----------------------------------------------------------- ");
OutputDebugString (BUF);
sprintf (buf, "total unfreed:%d bytes", totalsize);
      OutputDebugString (BUF);
  }; Now we have a reusable code to monitor and track all memory leaks. This code can be used to add to all the projects. It doesn't make your program look better, but at least it can help you check for errors and make the program more stable.

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.