mishmash
mishmash

Reputation: 4458

MinGW fprintf (vswprintf) causing a segmentation fault

I have the following example program that uses the preprocessor to define a simple debug function.

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;
}

I compile it with debug symbols and DEBUG defined, like so:

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

Now, when I compile this program and run it, I get a SIGSEGV with the following backtrace:

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) version is 4.8.1. Why is this crash occurring? How can it be fixed?

Upvotes: 0

Views: 675

Answers (2)

Sigcont
Sigcont

Reputation: 715

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;
}
~                                                                                 

~

Upvotes: 0

Paul R
Paul R

Reputation: 212969

The preprocessor macro __LINE__ is not a char *, it's an int, so:

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

needs to be:

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

Note that gcc would have warned you about this if were compiling with warnings enabled (e.g. gcc -Wall ...).

Upvotes: 1

Related Questions