内存分配成功并且已经初始化,但操作越过了内存的边界
内存分配成功并且已经初始化,但操作越过了内存的边界。
例如在使用数组时经常发生下标“多 1”或者“少 1”的操作。
特别是在 for 循环语 句中,循环次数很容易搞错,导致数组操作越界。
1 #include <iostream> 2 #include <string.h> 3 4 using namespace std; 5 //字符串输入函数 6 void str_input(char *p1,char *p2) 7 { 8 cout<<"string1:"; 9 cin>>p1; 10 cout<<"string2:"; 11 cin>>p2; 12 } 13 14 //显示strcmp()函数的比较结果 15 void strcmp_put(char *p1,char *p2) 16 { 17 cout<<"strcmp():"<<endl; 18 int result=strcmp(p1,p2); 19 if (result>0) 20 cout<<p1<<" greater than "<<p2<<endl; 21 if (result<0) 22 cout<<p1<<" less than "<<p2<<endl; 23 if (result==0) 24 cout<<p1<<" identical to "<<p2<<endl; 25 } 26 27 //显示stricmp()函数的比较结果 28 void stricmp_put(char *p1,char *p2) 29 { 30 cout<<"stricmp():"<<endl; 31 int result=stricmp(p1,p2); 32 if (result>0) 33 cout<<p1<<" greater than "<<p2<<endl; 34 if (result<0) 35 cout<<p1<<" less than "<<p2<<endl; 36 if (result==0) 37 cout<<p1<<" identical to "<<p2<<endl; 38 } 39 40 //显示strncmp()函数的比较结果 41 void strncmp_put(char *p1,char *p2,size_t count ) 42 { 43 cout<<"strncmp():"<<endl; 44 int result=strncmp(p1,p2,count); 45 if (result>0) 46 cout<<p1<<" greater than "<<p2<<endl; 47 if (result<0) 48 cout<<p1<<" less than "<<p2<<endl; 49 if (result==0) 50 cout<<p1<<" identical to "<<p2<<endl; 51 } 52 int main(int argc, char** argv) { 53 //声明字符数组 54 char str1[80],str2[80],p; 55 int i; 56 57 //测试测试各字符串比较函数 58 for(i=1;i<=3;i++) { 59 str_input(str1,str2); 60 strcmp_put(str1,str2); 61 stricmp_put(str1,str2); 62 strncmp_put(str1,str2,3); 63 cout<<"----------------------"<<endl; 64 } 65 return 0; 66 }