在C中使用sizeof

Ven*_*ta 0 c c++

我有以下程序,崩溃了.有谁知道它为什么会崩溃?

/* writes a, b, c into dst 
** dst must have enough space for the result 
** assumes all 3 numbers are positive */ 
void concat3(char *dst, int a, int b, int c) { 
    sprintf(dst, "%08x%08x%08x", a, b, c); 
} 

/* usage */ 
int main(void) { 
    printf("The size of int is %d \n", sizeof(int));
    char n3[3 * sizeof(int) + 1]; 
    concat3(n3, 0xDEADFACE, 0xF00BA4, 42); 
    printf("result is 0x%s\n", n3); 
    return 0; 
} 
Run Code Online (Sandbox Code Playgroud)

unw*_*ind 13

您将二进制数据的大小(这是什么sizeof)给您带来的混乱,以及十六进制的文本表示的大小,这是您要存储的内容.

在大多数当前系统上,sizeof(int)评估为4. n3因此,您的缓冲区将能够存储13个字符(3*4 + 1 == 13).

然后,将三个整数格式化为8个字符的十六进制格式,这将需要存储3*8 + 1 == 25个字符.结果缓冲区溢出导致崩溃.

很明显int,当您将其格式化为文本(并自己指定字段宽度!)时,数据类型的大小无关紧要.