请教,调用strcpy时出现的“写入位置 0x00388B30 时发生访问冲突。”

C++语言 码拜 7年前 (2017-04-13) 859次浏览
#define _CRT_SECURE_NO_DEPRECATE
#define _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES 1
#include<iostream>
#include<string>
using namespace std;
char* delc(char* s, char c)
{
char *p;
while (p = strchr(s, c))
{
strcpy(p, p + 1);
}
return s;
}
int main()
{
char*s = new char[20];
s = { “pen pineapple apple pen };
cout << s << endl;
delc(s, “p”);
cout << s << endl;
system(“pause”);
return 0;
}
在strcpy(p,p+1)处即出现访问冲突的错误,本人也试着逐行调试找出错误原因,但始终不知道怎么会出错
解决方案

10

strcpy两个参数不能指向同一片内存。

10

char*s = new char[20];
s = { "pen pineapple apple pen" };//执行这句后s指向常量字符串pen pineapple apple pen"的首地址

10

引用:
Quote: 引用:
int main()
{
char*s = new char[20];
s = { "pen pineapple apple pen" };//完全不知道你这行代码在写什么鬼,知道吗?这个s将会指向一个不可写内存,并不是你new出来的那块20,知道吗。这样的内存怎么写?
cout << s << endl;
delc(s, "p");
cout << s << endl;
system("pause");
return 0;
}

基础不牢,让人见笑了….那问一下应该怎么写呢

int main()
{
char*s = new char[100];//20明显太小
strcpy(s, "pen pineapple apple pen"); // 这样初化
cout << s << endl;
delc(s, "p");
cout << s << endl;
system("pause");
return 0;
}

20

strcpy要求你源地址与目标地址中的字符串不能重叠部分
你的strcpy(p, p + 1);  有重叠部分

5

#pragma comment(linker,"/SECTION:.rdata,RW")
//加这句可以让常量区可写,后果自负!

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明请教,调用strcpy时出现的“写入位置 0x00388B30 时发生访问冲突。”
喜欢 (0)
[1034331897@qq.com]
分享 (0)