测试因strcpy执行拷贝引起的内存溢出
#include "string.h" //strcpy()需要包含string.h头文件
typedef struct{
char buf1[5]; //声明char型数组buf1[]
char buf2[5]; //声明char型数组buf2[]
char buf3[10];//声明char型数组buf3[]
}MemoryStruct;
MemoryStruct MEM={0};
void Test_MemoryOverflow(void)
{
MEM.buf3[0]='1';MEM.buf3[1]='2';MEM.buf3[2]='3';
MEM.buf3[3]='4';MEM.buf3[4]='5';MEM.buf3[5]='6';MEM.buf3[6]='\0';
strcpy(MEM.buf1,MEM.buf3); //将buf3[]中的字符串拷贝到buf1[]中
}
仿真后,发现目标数组buf1[]不够大,而buf3[]中的源字符串的长度太长,会造成“内存溢出”,结果见下图:
同理可以测试strncpy()函数。