对于strcpy的数组越界,注意栈地址是从高到低的,即后分配的变量在低地址;而且char a[6]; char b[6]; a的地址可能是b的地址+12(vs 2012, 32bit)或者16(dev c++, g++, 32bit)
以下转自http://lixiaomeng.blog.51cto.com/3714496/982292
- #include<stdio.h>
- #include<string.h>
- void main()
- {
- char s[]="123456789";
- char d[]="123";
- strcpy(d,s);
- printf("d=%s,\ns=%s",d,s);
- }
- #include<stdio.h>
- #include<string.h>
- void main()
- {
- char d[]="123";
- char s[]="123456789";
- strcpy(d,s);
- printf("d=%s,\ns=%s",d,s);
- }
最后附上一个例子:
- //已知strcpy函数的原型是:
- char * strcpy(char * strDest,const char * strSrc);
- //实现代码
- char * strcpy(char * strDest,const char * strSrc)
- {
- if ((strDest==NULL)||(strSrc==NULL))
- throw "Invalid argument(s)";
- char * strDestCopy=strDest;
- while ((*strDest++=*strSrc++)!='\0');
- return strDestCopy;
- }
#include <stdio.h>
#include <algorithm>
#include <string>
#include <iostream>
#include <vector>
#include <string.h>
using namespace std;
struct {
char y;
char b[13];
char a[2];
int x;
} tmp;
int main() {
char a[]="12";
char b[] = "1234567890123456";
strcpy(a,b);
printf("%s\n",a);
printf("%s\n",b);
printf("a = %p\n",a);
printf("b = %p\n",b);
printf("a[4] = %c\n", a[4]);
printf("sizeof(b) = %d\n",sizeof(b));
printf("sizeof(a) = %d\n",sizeof(a));
printf("sizeof(tmp) = %d\n",sizeof(tmp));
return 0;
}
/*
int main()
{
char p[8];
char* s="123456789012345678";
strcpy(p,s);
cout << p << endl;
printf("p = %x\n",p);
printf("s = %x\n",s);
return 0;
}
*/
这里b的首地址 = a的首地址 + 20(dev c),注意a[4]也可以访问