Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!uflorida!uakari.primate.wisc.edu!aplcen!haven!adm!smoke!gwyn From: gwyn@smoke.BRL.MIL (Doug Gwyn) Newsgroups: comp.lang.c Subject: Re: __LINE__ and __FILE__ -- a beginner's question Message-ID: <11273@smoke.BRL.MIL> Date: 14 Oct 89 03:04:30 GMT References: <6257@arcturus> Reply-To: gwyn@brl.arpa (Doug Gwyn) Organization: Ballistic Research Lab (BRL), APG, MD. Lines: 32 In article <6257@arcturus> evil@arcturus.UUCP (Wade Guthrie) writes: >For what purpose are the __LINE__ and __FILE__ macros used? Are these >only useful for the writers of code that, in turn, produces compileable >code, or is there some use for the applications programmer? We've found them extremely helpful in identifying "memory leaks" (allocations without corresponding deallocations) and other such usage errors in a large project. The way we did this is typified by: #ifdef MmLOG extern pointer Mm_LQAllo( unsigned nbytes, const char *file, int line ); #define Mm_QAllo( nbytes ) Mm_LQAllo( nbytes, __FILE__, __LINE__ ) #else extern pointer Mm_QAllo( unsigned nbytes ); #endif The application uses Mm_QAllo() to allocate a chunk of memory and a similar Mm_QFree() function to deallocate it. When MmLOG is defined during compilation of the application, both these functions actually invoke a different function, Mm_LQAllo() or Mm_LQFree(), passing the application souce code file name and line number as arguments. The implementation of the Mm_L*() functions maintains internal data structures that keep track of all current allocations, and if an attempt is made to deallocate a not-currently-allocated block an error message results, containing the source code information giving the location of the erroneous Mm_QFree() call. Other checks are also made. At the end of application execution, an atexit()-registered function inspects the Mm_L*() data structures and lists all blocks that are considered still allocated. This should give some indication of how __LINE__ and __FILE__ can be useful.