fixed length data types in C/C++

后端 未结 11 1008
春和景丽
春和景丽 2020-12-23 14:34

I\'ve heard that size of data types such as int may vary across platforms.

My first question is: can someone bring some example, what goes wrong, when p

11条回答
  •  天涯浪人
    2020-12-23 15:12

    usually, the issue happens when you max out the number or when you're serializing. A less common scenario happens when someone makes an explicit size assumption.

    In the first scenario:

    int x = 32000;
    int y = 32000;
    int z = x+y;        // can cause overflow for 2 bytes, but not 4
    

    In the second scenario,

    struct header {
    int magic;
    int w;
    int h;
    };
    

    then one goes to fwrite:

    header h;
    // fill in h
    fwrite(&h, sizeof(h), 1, fp);
    
    // this is all fine and good until one freads from an architecture with a different int size
    

    In the third scenario:

    int* x = new int[100];
    char* buff = (char*)x;
    
    
    // now try to change the 3rd element of x via buff assuming int size of 2
    *((int*)(buff+2*2)) = 100;
    
    // (of course, it's easy to fix this with sizeof(int))
    

    If you're using a relatively new compiler, I would use uint8_t, int8_t, etc. in order to be assure of the type size.

    In older compilers, typedef is usually defined on a per platform basis. For example, one may do:

     #ifdef _WIN32
          typedef unsigned char uint8_t;
          typedef unsigned short uint16_t;
          // and so on...
     #endif
    

    In this way, there would be a header per platform that defines specifics of that platform.

提交回复
热议问题