Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Kinda disappointed that all five questions just boiled down to the size of structs / ints in memory. There's way more interesting and arcane gotchas in C!


Can you elaborate a bit? I don't know enough C to know many gotchas besides the order of the characters in i++ vs ++i mattering.


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/1e70e82baa9193f6f02...


That 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.


  puts("Hello World);

How does that even compile without the closing "?


The compiler isn’t strictly required by the standard to emit a syntax error when given an invalid program.


Every other one can be justified by the size of char/int are not fixed, but instead the standard defines a minimum size. Int is usually 32 bit but it's allowed to be 16 bit or anything larger. Char is usually 8 bit but can arbitrarily large if the platform "byte" is not 8 bits.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: