调试利用内存并释放内存的宏?
我编写了一个调试宏,并希望在其中包含时间,在本例中,我的函数 gettimestr()
接受一个小缓冲区(长度始终为 8,因为它的 sprintf
填充到 00:00:00
)并将其包含在 fprintf
中。我的宏如下所示:
#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
我的第一次尝试是让 gettimestr
返回一个 const char*
,但这很难释放内存,所以我继续使用缓冲区如果你能看到的话。
不幸的是,缓冲区不能使用两次(两个 DEBUGPRINT 将给出重新声明错误),而且我相信它不会释放内存,因为当 main 返回时它会消失,因为它不在函数中?
我的问题是:
- 我应该
malloc()
8 个字节(或者 9 个字节,如果 对于 \0,我不知道这是否是 现在需要)而不是[8],这样我就可以 在堆中按需释放它? - 我应该如何创建 缓冲、销毁引用和重用 它在另一个宏调用中修复我的 我无法调用它的问题 两次?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将允许多次使用并在每次使用后释放缓冲区。
Will allow multiple uses and deallocate the buffer after each use.
您应该分配 9 个字节来包含
'\0'
字节。最好的方法是通过代码中发布的数组来实现。为了克服双重定义的问题,您可以将其括在{}
中,例如: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.: