通常情况下,当您达到最大数量或进行序列化时,会出现此问题。较少见的情况是某人做出明确的大小假设。
在第一种情况下:
int x = 32000;
int y = 32000;
int z = x+y; // can cause overflow for 2 bytes, but not 4
在第二种情况下,
struct header {
int magic;
int w;
int h;
};
接下来会执行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
在第三种情况下:
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))
如果你使用的是相对较新的编译器,我建议使用uint8_t、int8_t等类型来确保类型大小。
在旧版本的编译器中,typedef通常是基于平台定义的。例如,可能会这样做:
#ifdef _WIN32
typedef unsigned char uint8_t;
typedef unsigned short uint16_t;
#endif
这样,每个平台都会有一个头文件,定义该平台的特定内容。
sizeof(void *)
肯定是4
”要好。) - Maciej Piechotka