C++ 程序接收信号SIGSEGV,分段故障。C++;
我在调试过程中遇到这个错误(*s=*end;line),同时尝试使用指针反转字符串。 我正在使用Windows10操作系统、代码块IDE和GDB调试器C++ 程序接收信号SIGSEGV,分段故障。C++;,c++,segmentation-fault,codeblocks,C++,Segmentation Fault,Codeblocks,我在调试过程中遇到这个错误(*s=*end;line),同时尝试使用指针反转字符串。 我正在使用Windows10操作系统、代码块IDE和GDB调试器 #include <stdio.h> #include <string.h> #include <limits.h> void myreverse(char* s); int main() { char* s1 = "1234"; myreverse(s1); printf("%s"
#include <stdio.h>
#include <string.h>
#include <limits.h>
void myreverse(char* s);
int main()
{
char* s1 = "1234";
myreverse(s1);
printf("%s", s1);
return 0;
}
void myreverse(char* s) {
char tmp;
char* end = s + strlen(s) - 1;
for(; s < end; s++, end--) {
tmp = *s;
*s = *end;
*end = tmp;
}
}
#包括
#包括
#包括
void myreverse(字符*s);
int main()
{
char*s1=“1234”;
myreverse(s1);
printf(“%s”,s1);
返回0;
}
void myreverse(字符*s){
char-tmp;
char*end=s+strlen(s)-1;
对于(;s
您应该将s1
更改为char s1[]=“1234”代码>因为您正在更改字符串
然后在myreverse()
函数中,从不使用tmp
变量,这会导致交换块失败
固定的:
#include <cstdio> // use the C++ versions of the header files
#include <cstring>
void myreverse(char* s) {
char tmp;
char* end = s + std::strlen(s) - 1;
for(; s < end; s++, end--) {
// swap
tmp = *s;
*s = *end;
*end = tmp; // use tmp
}
}
int main() {
char s1[] = "1234";
myreverse(s1);
printf("%s", s1);
}
<代码>包含/ /使用头文件的C++版本
#包括
void myreverse(字符*s){
char-tmp;
char*end=s+std::strlen(s)-1;
对于(;s
请注意,交换块中的3行可以替换为,并且
myreverse()
可以完全替换为。char*s1=“1234”代码>应该是const char*s1=“1234”代码>或字符s1[]=“1234”代码>如果您想更改它。^^^^^^这将破坏您的构建,而不是像现在这样调用未定义的行为。不要惊讶,这就是你在这种情况下想要的,因为它指出了真正的问题。然后,更改常量char*s1=“1234”代码>至字符s1[]=“1234”代码>,并给它另一个rip。它看起来也像*end=*s代码>应该是*end=tmp代码>。