-1

I want to define a marco to do "print on console and write to file". Below is my code, may somebody show me why it resulted by "Segmentation fault (core dumped)".

#define TRC_DP(fmt, args...)  \
do {\
    FILE * fp = fopen("/home/debug.log","a+");\
    fprintf(fp,"TRC_DP(%s:%d):\t" fmt, __func__, __LINE__, ##args);\
    printf(fmt, ##args);\
    fclose(fp);\
}while(0);
David Ranieri
  • 39,972
  • 7
  • 52
  • 94
  • 4
    The macro should not end with a semicolon. – pmg Mar 16 '17 at 09:51
  • 1
    That usage of `arg...` is not standard C. Even if you have a variadic macro in standard C, nobody can help you unless you provide an example of USAGE of the macro that results in the error. – Peter Mar 16 '17 at 10:01
  • Why are you doing it with a macro? Write a _function_ `int TRC_DP(const char *, ...)` and use one of the `vsprintf` variants inside `myprintf`. – Jabberwocky Mar 16 '17 at 10:21
  • I've got a fortune cookie in my lunch today, it says "Your $HOME is writable but /home is not", but I have no idea what it's talking about. – n. m. could be an AI Mar 16 '17 at 10:22
  • 1
    @n.m. It probably means that you should block third-party fortune cookies. – Lundin Mar 16 '17 at 15:00

1 Answers1

3

Here are some bugs:

  • TRC_DP(fmt, args...) is not valid standard C.
  • The icky do-while(0) trick assumes that there is no trailing semi-colon.
  • You must always check if fopen was successful.

Something like this might solve the problems:

#define TRC_DP(fmt, ...)  \
do {\
    FILE * fp = fopen("/home/debug.log","a+");\
    if(fp != NULL) { \
      fprintf(fp,"TRC_DP(%s:%d):\t" fmt, __func__, __LINE__, __VA_ARGS__); \
      printf(fmt, __VA_ARGS__);\
      fclose(fp);\
    } \
}while(0)

However, this is some seriously ugly code. You should replace this with a function and concatenate the format strings in run-time, if you must.

Overall, you should avoid variable argument functions or macros whenever possible. They are not only ugly but also very dangerous. The presence of variable arguments is usually a very strong indication of poor program design.

Community
  • 1
  • 1
Lundin
  • 195,001
  • 40
  • 254
  • 396