You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Valgrind报告未初始化值大小为8的疑问(x64环境sizeof(int)=4)

Understanding Valgrind's "Use of uninitialised value of size 8" on x64 with 4-byte ints

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.
  • s is declared but not initialized, yet you use it in s += 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:

  1. Default Argument Promotions
    On x86_64 (64-bit) systems, when you pass an int to a variadic function like printf, it gets automatically promoted to long (which is 8 bytes on x64). Even though your a[2] is a 4-byte int, it's expanded to an 8-byte value when passed to printf. Valgrind tracks the entire 8-byte region used by the library function, hence the "size 8" message.

  2. Libc Internal Handling
    The error traces back to functions like _itoa_word and vfprintf—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 from a[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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 03:59:02