4 ms·
Something as simple as adding integers is tricky due to its implicitness. Due to promotion, the following code works on some platforms but is verboten on others
by skitter 3y ago
Something as simple as adding integers is tricky due to its implicitness. Due to promotion, the following code works on some platforms but is verboten on others:
int16_t a = 20000;
int16_t b = a + a;
But even ignoring size, it can bite you:
unsigned int c = 1;
signed int d = -2;
if(c + d > 0)
puts("1 + -2 > 0");
That code prints because of balancing: The signed value gets cast to an unsized int, which can't hold the value.
For not directly integer related semantics, creating an out-of-bounds pointer is UB, unless it points to one past the end of the object, in which case you can create the pointer but can't read from it. And if an object's lifetime has ended, pointers to it aren't valid anymore even if you don't even read from it:
void *foo_1 = malloc(1);
free(foo_1);
void *foo_2 = malloc(1);
printf("Checking for same allocatoin: %d", foo_1 == foo_2);
If you go by the standard, strictly speaking this is UB:
#include <stdio.h>
int main(void) {
puts("Hello World);
}
But don't worry, real compilers will refuse to compile this. Most don't follow the standard anyways, because they don't treat writing to a memory location as side effect.
A large source of gotchas in C are the standard libraries. For example here's a taste of the trouble its locales cause:
https://github.com/mpv-player/mpv/commit/1e70e82baa9193f6f027338b0fab0f5078971fbe https://github.com/mpv-player/mpv/commit/1e70e82baa9193f6f02...
- smcameron 3y agoThat last link was enjoyable. The best way I know of to amputate locales is to use dlsym() to look up setlocale() and replace it with your own setlocale that calls the real setlocale with arguments LC_ALL, "C", regardless of what arguments are passed in.
- readthenotes1 3y agoputs("Hello World); How does that even compile without the closing "?
- P-Nuts 3y agoThe compiler isn’t strictly required by the standard to emit a syntax error when given an invalid program.