home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #27 / NN_1992_27.iso / spool / comp / lang / cplus / 16793 < prev    next >
Encoding:
Text File  |  1992-11-23  |  2.3 KB  |  61 lines

  1. Newsgroups: cvnet.c++,comp.lang.c++
  2. Path: sparky!uunet!taumet!steve
  3. From: steve@taumet.com (Steve Clamage)
  4. Subject: Re: Finding memory leaks
  5. Message-ID: <1992Nov23.210418.4537@taumet.com>
  6. Keywords: OOP,memory leaks
  7. Organization: TauMetric Corporation
  8. References: <1992Nov20.191828.14500@ultb.isc.rit.edu> <1992Nov22.181937.2176@taumet.com> <9232813.12737@mulga.cs.mu.OZ.AU>
  9. Date: Mon, 23 Nov 1992 21:04:18 GMT
  10. Lines: 49
  11.  
  12. fjh@munta.cs.mu.OZ.AU (Fergus James HENDERSON) writes:
  13.  
  14. >steve@taumet.com (Steve Clamage) writes:
  15.  
  16. >>mpk9172@ultb.isc.rit.edu (M.P. Kirby) writes:
  17. >>
  18. >>>In C I used to use a memory leak finder that would help me find
  19. >>>my memory leaks.  I basically created a #define for malloc that redefined
  20. >>>it ...
  21.  
  22. >>>I would like to do the same kind of thing in C++...
  23.  
  24. >>You do NOT want to replace "new" with a macro.  "new" is
  25. >>a keyword which causes constructors to be called, and memory to be
  26. >>allocated via the function "operator new()".  If you replace the "new"
  27. >>keyword with a macro, you destroy the semantics of most programs.
  28.  
  29. >Unfortunately, we DO want to replace "new" with a macro, so that we can
  30. >get __LINE__ and __FILE__. Redefining operator new() is not sufficient, because
  31. >__LINE__ inside operator new() refers to the line where operator new() was
  32. >redefined, not the line where new was invoked. ...
  33.  
  34. >The only way that I can see of solving the problem is to write a preprocessor
  35. >which properly parses the source code, and then does the desired replacements.
  36. >I don't see how it could be done using just the simple textual substitution
  37. >provided by the C preprocessor.
  38.  
  39. If you don't mind modifying the source code, you can use placement syntax.
  40. For example, instead of
  41.         T* p = new T;
  42. you would use
  43.         T* p = new (__FILE__, __LINE__) T;
  44. The result would be a call to
  45.         operator new(size_t size, char* file, int line)
  46. which would be your specialized allocation function.
  47.  
  48. You could use a macro to make this less tedious:
  49.     #define my_new(x)    new (__FILE__, __LINE__) x
  50.     ...
  51.     T* p = my_new(T);
  52.  
  53. Then write your own operator delete.  You have to be aware that there may
  54. be calls to ordinary operator new from the library or other code.  Your
  55. operator delete has to be able to cope with both, since there can be
  56. only one (global) operator delete in the system.
  57. -- 
  58.  
  59. Steve Clamage, TauMetric Corp, steve@taumet.com
  60. Vice Chair, ANSI C++ Committee, X3J16
  61.