1

I have defined an assert function, just to print the function name and line number, but I get Segmentation fault (core dumped), how to fix it?

#define assert( string ) \
    printf("%s - %s assert %s\n",__FUNCTION__, __LINE__,  #string);
int main(int argc, char **argv)
{
    assert( "test assert" );
    printf("%s(%d)-%s: this is main\n",__FILE__,__LINE__,__FUNCTION__);
    return 0;
}

the ultimate target is to define the function to print all the info passed by parameter like printf receive unlimited parameters.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
river
  • 694
  • 6
  • 22
  • 1
    `__LINE__` is an `int`, not a string. You need to use it with `%d`, not `%s`. Also, `#string` *stringizes* the argument, but you're already passing it a string. This question also doesn't have anything to do with receiving an unlimited number of arguments... – jamesdlin Nov 03 '14 at 04:02
  • Thanks! @Paul Rooney solves all my questions. – river Nov 03 '14 at 07:32

1 Answers1

1

Given your question I've assumed you are asking for an assert macro.

When you assert you assert on a condition being true or false. You don't just pass it a string.

Try this

#define ASSERT(cond_, fmt, ...) do                              \
                    {                                           \
                        if(!(cond_))                            \
                        {                                       \
                            printf("assert: file %s line %d ",  \
                            __FILE__, __LINE__);                \
                            fprintf(stderr, fmt, __VA_ARGS__);  \
                            fflush(stderr);                     \
                            abort();                            \
                        }                                       \
                    } while(0)

For gcc the fprintf line must be defined as

fprintf(stderr, fmt, ##__VA_ARGS__);  \

It is a good strategy however to define your assert functionality as a function and wrap this function in a macro.

  • The macro facilitates easy disabling of the assert in a release build.
  • The function gives you a great place to put a breakpoint when debugging.
Paul Rooney
  • 20,879
  • 9
  • 40
  • 61