I wrote a debug macro and wanted to include time in it, in this case my gettimestr() function takes a small buffer (always 8 in length, because its sprintf overlays at 00:00:00 ) and includes with fprintf inside. My macro looks like this:
#define _DEBUGPRINT(...) fprintf(stderr, __VA_ARGS__); #ifndef NDEBUG # define WHERESTR "[[%s] file %s, line %d]: " # define WHEREARG timebufstr_0, __FILE__, __LINE__ # define DEBUGPRINT(_fmt, ...) \ char timebufstr_0[8]; \ gettimestr( timebufstr_0 );\ _DEBUGPRINT(WHERESTR _fmt, WHEREARG, __VA_ARGS__) #else # define DEBUGPRINT(_fmt, ...) #endif
My first attempt was to gettimestr return a const char* , but it is hard to free memory, so I went ahead and used a buffer if you can see.
Unfortunately, the buffer cannot be used twice (two DEBUGPRINT will give a re-allocation error), and also I believe that it will not free memory, because it will disappear when main returns, because it is not in the function?
My questions:
- Do I have to
malloc() 8 bytes (or 9 if for \ 0, I donβt know if it is required now) instead of [8], so can I get it free on demand in a heap? - How can I create buffers, destroy links, and reuse this in another macro call to fix my problem when I couldn't name it twice?
source share