Debugging a macro that uses memory and frees it up?

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?
+4
source share
2 answers
 #define _DEBUGPRINT(...) fprintf(stderr, __VA_ARGS__); #ifndef NDEBUG # define WHERESTR "[[%s] file %s, line %d]: " # define WHEREARG timebufstr_0, __FILE__, __LINE__ # define DEBUGPRINT(_fmt, ...) \ do { \ char timebufstr_0[8]; \ gettimestr( timebufstr_0 );\ _DEBUGPRINT(WHERESTR _fmt, WHEREARG, __VA_ARGS__) \ } while (0); #else # define DEBUGPRINT(_fmt, ...) /**/ #endif 

Allows multiple use and free the buffer after each use.

+3
source

You must allocate 9 bytes to include the byte '\0' . The best way is to do this with an array located in your code. To overcome the problems of double definition, you can enclose it in {} , for example:

 #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[9]; \ gettimestr( timebufstr_0 );\ _DEBUGPRINT(WHERESTR _fmt, WHEREARG, __VA_ARGS__)\ } // <--------- #else # define DEBUGPRINT(_fmt, ...) /**/ #endif 
0
source

Source: https://habr.com/ru/post/1344591/


All Articles