This documentation is copyright © 1998-2001 Sandro Sigala <sandro@sigala.it>.
All rights reserved.

Released under the GNU General Public License.

Return to index Return to header Previous symbol Next symbol

assert

Prototype

#include <assert.h>

void assert(int expression);

Description

Prints an error message to standard output and terminates the program by calling the abort function if the argument expression is false. This only happens when the macro NDEBUG is undefined before the inclusion of the <assert.h> header, usually during the editing-debug phase of the software development. The assert argument should not have side-effects, because the program behavior will be different depending whether NDEBUG is defined, as in this example:
char *s;
assert((s = (char *)malloc(FILENAME_MAX)) != NULL);
strcpy(s, otherstr);

Implementation

Implementation of the <assert.h> standard header:
#undef assert

#ifdef NDEBUG #define assert(e) ((void)0) #else void __assert_error(char *expr, char *filename, unsigned int line); #define assert(e) ((void)(e || __assert(#e, __FILE__, __LINE__)))
Implementation of the __assert_error function referenced by the assert macro in the <assert.h> header:
#include <stdio.h>
#include <stdlib.h>

void __assert_error(char *expr, char *filename, unsigned int line) { fprintf(stderr, "Assertion failed: %s, file %s, line %d\n", expr, filename, line); abort(); }

Example

View source
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>

/*
 * Return a pointer to an allocated region of memory of the
 * specified size.  Check for unexpected errors.
 */
void *xmalloc(size_t size)
{
    void *p;

    assert(size > 0);
    if ((p = malloc(size)) == NULL) {
	fprintf(stderr, "No more available memory\n");
	exit(1);
    }

    return p;
}

References

ISO C 9899:1990 7.2.1.1, ISO C 9899:1999 7.2.1.1