一 点睛
对于位于程序中的不同段的变量,其初始值是不同的,全局变量和静态变量初始值为0,而局部变量和动态申请的变量,其初始值为随机值。如果程序使用了为随机数的变量,那么程序的行为就变得不可预期了。
二 错误代码
#include<iostream>
using namespace std;
int main(){
int a[5];
int i,s=0;
a[0]=a[1]=a[3]=a[4]=0;
for(i=0;i<5;i++)
s=s+a[i];
if(s==33)
cout<<"sum is 33"<<endl;
else
cout<<"sum is not 33"<<endl;
return 0;
}
三 编译并运行
[root@localhost charpter05]# g++ -g 0509test.cpp -o 0509
[root@localhost charpter05]# ./0509
sum is not 33
四 用Valgrind检测使用未初始化的内存
[root@localhost charpter05]# valgrind ./0509
==17792== Memcheck, a memory error detector
=