开发者

Debugging macro that utilizes memory and frees in it?

I have written a debugging macro and wished to include the time in it, in this case my function gettimestr() accepts a small buffer (always 8 in length, because its sprintf pads to 00:00:00) and include that with the fprintf within. My macro looks like the following:

#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 have gettimestr return a const char*, but that is hard to free memory of so I went ahead and used a buffer if you can see.

Unfortunately the buffer cannot be used twice (开发者_开发百科two DEBUGPRINTs will give a redeclaration error) and also I believe it won't free the memory because it will disappear when main returns, as it is not in a function?

My questions are:

  • Should I malloc() 8 bytes (or 9 if for \0, I am unaware if that is required now) instead of [8] so I can free it on demand in the heap?
  • How should I be able to create the buffer, destroy references, and reuse it in another macro call to fix my problem where I could not call it twice?


#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

Will allow multiple uses and deallocate the buffer after each use.


You should allocate 9 bytes for including the '\0' byte. The best way is to make it via a an array as posted in your code. For overcomming the problems of double-definition, you can enclose it in {}, e.g.:

#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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜