Valgrind报告未初始化值大小为8的疑问(x64环境sizeof(int)=4)
Great question—let's break this down clearly to resolve your confusion. First, let's spot the root uninitialized values in your code:
a[2]is never assigned a value, but you print it directly on line 9.sis declared but not initialized, yet you use it ins += a[i](line 11) and a conditional check (line 13).
Now, why does Valgrind report "size 8" when sizeof(int) is 4? This has nothing to do with pointers—it's all about how 64-bit systems handle function arguments and internal library logic:
Default Argument Promotions
On x86_64 (64-bit) systems, when you pass anintto a variadic function likeprintf, it gets automatically promoted tolong(which is 8 bytes on x64). Even though youra[2]is a 4-byte int, it's expanded to an 8-byte value when passed toprintf. Valgrind tracks the entire 8-byte region used by the library function, hence the "size 8" message.Libc Internal Handling
The error traces back to functions like_itoa_wordandvfprintf—these standard library functions use 64-bit variables/registers to process numeric values for printing. When they receive the promoted 8-byte value (where the lower 4 bytes are uninitialized froma[2], and the upper 4 bytes are random stack garbage), Valgrind flags the entire 8-byte block as uninitialized.
Fixing the Issues
To eliminate all Valgrind errors, simply initialize both uninitialized variables:
#include <stdio.h> int main() { int a[5]; int i,s=0; // Initialize s to 0 a[0]=a[1]=a[2]=a[3]=a[4]=0; // Initialize a[2] printf("%d\n",a[2]); for(i=0;i<5;i++) s += a[i]; if(s == 377) printf("sum is %d\n",s); return 0; }
Recompile with gcc -g -o sample2 sample2.c and run Valgrind again—all uninitialized value errors will disappear. The error related to s on line 13 also vanishes because we fixed its initial state, stopping the uninitialized value from propagating through the sum operation.
内容的提问来源于stack exchange,提问作者J.Doe

