Phil CK

Segfault!

Last updated on

Segfaults are a pain, but usually they something along these lines.

/* segfault.c */

#include <stdio.h>
#include <stdlib.h>


#ifndef SEGFAULT
#define SEGFAULT 0
#endif


int
main() {

        int *value = NULL;

        if(!SEGFAULT) {
                value = malloc(sizeof(*value));
                *value = 123;
        }

        printf("value of int is: %d\n", *value);

        return 0;
}

Compile and run,

gcc segfault.c -DSEGFAULT=1 && ./a.out

outputs (or something similar) …

Segmentation fault (core dumped)

Compile and run,

gcc segfault.c -DSEGFAULT=0 && ./a.out

outputs …

value of int is 123