尝试创建一个宏,可以在定义DEBUG时用于打印调试消息,如下面的伪代码:
#define DEBUG 1
#define debug_print(args ...) if (DEBUG) fprintf(stderr, args)
Run Code Online (Sandbox Code Playgroud)
如何用宏实现这一目标?
以下代码已编译,gcc-5.4.0没有任何问题:
% gcc -W -Wall a.c\n...\n\n#include <stdio.h>\n#include <stdarg.h>\n\nstatic int debug_flag;\nstatic void debug(const char *fmt, ...)\n{\n va_list ap;\n\n va_start(ap, fmt);\n vfprintf(stderr, fmt, ap);\n va_end(ap);\n}\n\n#define DEBUG(...) \\\n do { \\\n if (debug_flag) { \\\n debug("DEBUG:"__VA_ARGS__); \\\n } \\\n } while(0)\n\nint main(void)\n{\n int dummy = 10;\n debug_flag = 1;\n DEBUG("debug msg dummy=%d\\n", dummy);\n return 0;\n}\nRun Code Online (Sandbox Code Playgroud)\n然而,编译它g++会产生有趣的效果:
% g++ -W -Wall -std=c++11 a.c\na.c: In function \xe2\x80\x98int main()\xe2\x80\x99:\na.c:18:10: error: unable to find string literal operator \xe2\x80\x98operator""__VA_ARGS__\xe2\x80\x99 with \xe2\x80\x98const …Run Code Online (Sandbox Code Playgroud) 美好的一天!
我正在玩一个C项目.它位于FreeBSD机器上(它看起来像Raspberry PI2,不确定)
问题是我想在Valgrind中运行项目来查找内存泄漏.当我尝试通过端口安装Valgrind时,我得到下一个错误:
root@raspberry-2-55:/usr/ports/devel/valgrind # make
===> valgrind-3.10.1.20160113,1 is only for i386 amd64, while you are running
armv6.
*** Error code 1
Stop.
make: stopped in /usr/ports/devel/valgrind
Run Code Online (Sandbox Code Playgroud)
请帮助在这个平台上运行valgrind.
我正在实施我自己的fast_malloc()来替换malloc(). 我需要在里面调试打印。是否有任何打印调用保证永远不会调用malloc(),或者我是否需要创建自己的安全版本?
以前,我不小心通过调用导致了无限递归malloc(),printf()然后调用malloc(),然后调用printf()...永远。
如果我需要创建自己的安全版本,在后台使用固定大小的静态数组作为要格式化的缓冲区,这就是我需要知道的。我能做到。
puts()或者怎么样putc()?他们应该很安全,不是吗?
我使用的是 Linux Ubuntu 20.04。理想情况下,我所做的一切都将是跨平台兼容的,但我想如果需要低级系统调用,我可以自定义。
snprintf():调用 malloc 的 snprintf 或不调用 malloc 的 snprintf