#include <iostream>
using namespace std;
void *mymemcpy(void *dest, const void *src, size_t num)
{
if (src == NULL || dest == NULL)
return NULL;
char const *psrc = (char *)(src);
char *pdest = (char *)(dest); //强制将void *转换成char* 类型
size_t i;
if (psrc < pdest&&pdest < psrc + num) //src和dest地址重叠,开始逆序复制
{
for (i = num - 1; i != -1; i--)
{
pdest[i] = psrc[i];
}
}
else {
for (i = 0; i < num; i++)
{
pdest[i] = psrc[i];
}
}
return dest;
}
int main(void)
{
char src[] = "abc";
char *dest = src + 1;
dest = (char *)mymemcpy(dest, src, 4);
printf("%s\n", dest);
system("pause");
return 0;
}
因为src和dest存在内存重叠,在内存拷贝时,src的'\0'在拷贝过程中被覆盖,运行结果:
abc
请按任意键继续. . .
按任意键后报错Run-Time Check Failure #2 - Stack around the variable 'src' was corrupted.该怎么解决?
4 个解决方案
#1
加个缓冲区,先拷贝到这里,再拷贝到目标
#2
memmov?
#3
轻易越界真不是个好习惯
#4
仅供参考:
#include <stdio.h>
#include <string.h>
char s[256];
char *p;
int r,n,i;
int main() {
while (1) {
printf("请输入一行文字(空行结束),\"%%20\"将替换为\" \",\"你懂得\"将替换为\"XXXXXX\":\n");
fgets(s,256,stdin);
if ('\n'==s[0]) break;
p=s;
while (1) {
p=strstr(p,"%20");
if (p) {
memmove(p+1,p+3,strlen(p)-3+1);
p[0]=' ';
} else break;
}
p=s;
while (1) {
p=strstr(p,"你懂得");
if (p) {
memmove(p+6,p+6,strlen(p)-6+1);
for (i=0;i<6;i++) p[i]='X';
} else break;
}
printf("%s",s);
}
return 0;
}
//请输入一行文字(空行结束),"%20"将替换为" ","你懂得"将替换为"XXXXXX":
//abcdefg%20helloworld%20something.pdf
//abcdefg helloworld something.pdf
//请输入一行文字(空行结束),"%20"将替换为" ","你懂得"将替换为"XXXXXX":
//这是测试文字你懂得,在这个你懂的地方,就得做你懂得的事
//这是测试文字XXXXX,在这个你懂的地方,就得做XXXXX的事
//请输入一行文字(空行结束),"%20"将替换为" ","你懂得"将替换为"XXXXXX":
//
#1
加个缓冲区,先拷贝到这里,再拷贝到目标
#2
memmov?
#3
轻易越界真不是个好习惯
#4
仅供参考:
#include <stdio.h>
#include <string.h>
char s[256];
char *p;
int r,n,i;
int main() {
while (1) {
printf("请输入一行文字(空行结束),\"%%20\"将替换为\" \",\"你懂得\"将替换为\"XXXXXX\":\n");
fgets(s,256,stdin);
if ('\n'==s[0]) break;
p=s;
while (1) {
p=strstr(p,"%20");
if (p) {
memmove(p+1,p+3,strlen(p)-3+1);
p[0]=' ';
} else break;
}
p=s;
while (1) {
p=strstr(p,"你懂得");
if (p) {
memmove(p+6,p+6,strlen(p)-6+1);
for (i=0;i<6;i++) p[i]='X';
} else break;
}
printf("%s",s);
}
return 0;
}
//请输入一行文字(空行结束),"%20"将替换为" ","你懂得"将替换为"XXXXXX":
//abcdefg%20helloworld%20something.pdf
//abcdefg helloworld something.pdf
//请输入一行文字(空行结束),"%20"将替换为" ","你懂得"将替换为"XXXXXX":
//这是测试文字你懂得,在这个你懂的地方,就得做你懂得的事
//这是测试文字XXXXX,在这个你懂的地方,就得做XXXXX的事
//请输入一行文字(空行结束),"%20"将替换为" ","你懂得"将替换为"XXXXXX":
//