HiveBrain v1.2.0
Get Started
← Back to all entries
debugcModerate

abort() implementation

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
implementationabortstackoverflow

Problem

Here you go:

#define abort(msg) (fprintf(stderr, msg) && *((char*)0))

Solution

Non-standard interface to standard function

The obvious criticism of that implementation is that it has a different interface from what the C standard requires:


§7.20.4.1 The abort function


Synopsis

#include 
void abort(void);




Description


The abort function causes abnormal program termination to occur, unless the signal
SIGABRT is being caught and the signal handler does not return. Whether open streams
with unwritten buffered data are flushed, open streams are closed, or temporary files are
removed is implementation-defined. An implementation-defined form of the status
unsuccessful termination is returned to the host environment by means of the function
call raise(SIGABRT).


Returns


The abort function does not return to its caller.

Unreliable implementation of 'crash'

There were systems, notoriously the DEC VAX, where accessing the memory at address 0 did not cause problems (until the programs that were written on the VAX were ported to other platforms that did abort).

Dereferencing a null pointer is undefined behaviour - that means anything could happen, including 'no crash'.

Nitpicks in implementation

If, for some reason, fprintf() returns 0, your program will not abort. For example:

abort("");


does not abort. It is also dangerous to use the string as the format string; you should use:

#define abort(msg) (fprintf(stderr, "%s\n", msg) && *((char*)0))


It would be better to use a comma operator in place of the &&:

#define abort(msg) (fprintf(stderr, "%s\n", msg), raise(SIGABRT))


Since the standard library could have defined a macro abort(), you should #undef it before defining it yourself.

Code Snippets

#include <stdlib.h>
void abort(void);
#define abort(msg) (fprintf(stderr, "%s\n", msg) && *((char*)0))
#define abort(msg) (fprintf(stderr, "%s\n", msg), raise(SIGABRT))

Context

StackExchange Code Review Q#551, answer score: 16

Revisions (0)

No revisions yet.