Skip to content

Instantly share code, notes, and snippets.

@theteachr
Last active July 1, 2022 12:21
Show Gist options
  • Save theteachr/562258d93982dc1040f3335df466debe to your computer and use it in GitHub Desktop.
Save theteachr/562258d93982dc1040f3335df466debe to your computer and use it in GitHub Desktop.
Compiler Optimization Behavior: Short Circuiting
#include <stdio.h>
#include <stdlib.h>
struct Reeds {
int store;
};
int main(void) {
struct Reeds* r = NULL;
// r = malloc(sizeof(struct Reeds));
printf("%d\n", r->store == 0 && r != NULL);
return 0;
}
/*
* Running with `-O1` seems to run the null check before accessing the
* struct member (swap the sides of the boolean expression).
*
* (This behavior might already be listed in the docs of the `O` flag.)
*
* Command outputs:
*
* $ gcc -O1 main.c && ./a.out
* 0
*
* $ gcc -O0 main.c && ./a.out
* zsh: segmentation fault ./a.out
*
*
* $ clang -O1 main.c && ./a.out
* 0
*
* $ clang -O0 main.c && ./a.out
* zsh: segmentation fault ./a.out
*
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment