MinGW fprintf(vswprintf)导致分段错误

时间:2015-11-09 08:58:04

标签: c gcc mingw

我有以下示例程序,它使用预处理器来定义一个简单的调试函数。

的main.c

#include <stdio.h>
#ifdef DEBUG
#define __DEBUG 1
#else
#define __DEBUG 0
#endif
#define dbg_out(fmt, ...) \
    do {if (__DEBUG) fprintf(stdout, "%s:%s:%s():" fmt "\n", __FILE__, \
                           __LINE__, __FUNCTION__, __VA_ARGS__); } while (0)

int main (int argc, char **argv)
{
    dbg_out ("Printing argc: %d", argc);
    return 0;
}

我使用调试符号和DEBUG定义编译它,如下所示:

gcc main.c -g -DDEBUG -o test.exe

现在,当我编译该程序并运行它时,我得到一个带有以下回溯的SIGSEGV

Program received signal SIGSEGV, Segmentation fault.
0x75b7b090 in vswprintf () from C:\Windows\SysWOW64\msvcrt.dll

(gdb) bt

#0  0x75b7b090 in vswprintf () from C:\Windows\SysWOW64\msvcrt.dll
#1  0x75b73633 in msvcrt!fprintf () from C:\Windows\SysWOW64\msvcrt.dll
#2  0x75bb1228 in msvcrt!_iob () from C:\Windows\SysWOW64\msvcrt.dll
#3  0x0040a070 in __register_frame_info ()
#4  0x00401425 in main (argc=1, argv=0x4a2f08) at src/main.c:16

GCC(MinGW)版本为4.8.1。为什么会发生这种崩溃?如何解决?

2 个答案:

答案 0 :(得分:1)

预处理器宏__LINE__不是char *,而是int,所以:

#define dbg_out(fmt, ...) \
    do {if (__DEBUG) fprintf(stdout, "%s:%s:%s():" fmt "\n", __FILE__, \
                           __LINE__, __FUNCTION__, __VA_ARGS__); } while (0)

需要:

#define dbg_out(fmt, ...) \
    do {if (__DEBUG) fprintf(stdout, "%s:%d:%s():" fmt "\n", __FILE__, \
                           __LINE__, __FUNCTION__, __VA_ARGS__); } while (0)

请注意,如果在启用警告的情况下进行编译,gcc会向您发出警告(例如gcc -Wall ...)。

答案 1 :(得分:0)

Please refer the following code.

    #include <stdio.h>
#define DEBUG 1
#ifdef DEBUG
#define __DEBUG 1
#else
#define __DEBUG 0
#endif
#define dbg_out(fmt, ...) \
    do {if (__DEBUG) fprintf(stdout, "%s:%d:%s():" fmt "\n", __FILE__, \
                           __LINE__, __FUNCTION__, __VA_ARGS__); } while (0)

int main (int argc, char **argv)
{
    dbg_out ("Printing argc: %d", argc);
    return 0;
}
~                                                                                 

相关问题