Last active
July 1, 2022 12:21
-
-
Save theteachr/562258d93982dc1040f3335df466debe to your computer and use it in GitHub Desktop.
Compiler Optimization Behavior: Short Circuiting
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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