[英]String reversal in C++ getting 'Segmentation fault (core dumped) error
This below gives me 'Segmentation fault (core dumped)' error after printing the reversed string. 打印反向字符串后,下面的错误提示我“ Segmentation fault(core dumped)”错误。 Can anyone explain why ?
谁能解释为什么?
#include <iostream>
#include <string>
#include <cstdio>
using namespace std;
void print (char *str) {
if (*str) {
print (str+1);
cout << *str;
}
}
int main() {
char *str;
cin >> str;
print(str);
cout << endl;
return 0;
}
Uninitialized non-static local variables have an indeterminate value, and will in reality be seemingly random. 未初始化的非静态局部变量具有不确定的值,实际上似乎是随机的。 Using them without initialization leads to undefined behavior , which is one of the most common causes of crashes.
在没有初始化的情况下使用它们会导致未定义的行为 ,这是崩溃的最常见原因之一。
The problem is that you have a pointer, but it doesn't point anywhere so when you use it to read input, the input stream cin
will write to a random location in memory. 问题是您有一个指针,但是它没有指向任何地方,因此当您使用它来读取输入时,输入流
cin
将写入内存中的随机位置。
The solution is to not use character pointers for string, but the std::string
class. 解决方案是不要将字符指针用于字符串,而应使用
std::string
类。
If you have to use pointers, then you have two solutions: Either declare the string as an array, or allocate memory using the new
operator. 如果必须使用指针,则有两种解决方案:将字符串声明为数组,或使用
new
运算符分配内存。 However be cautioned that if you input more than you have allocated you will write out of bounds and once again have undefined behavior . 但是请注意,如果输入的内容超出分配的范围,则会超出范围,并再次出现未定义的行为 。
You have not allocated any memory to char *str
. 您尚未为
char *str
分配任何内存。 Try using char str[20]
(20 is just an example, it could be anything as per your demand and your machine's capability) and everything will be fine. 尝试使用
char str[20]
(20只是一个示例,可以根据您的需求和计算机的性能进行选择),一切都会很好。 You are assuming that compiler will allocate memory for you but that's not the case. 您假设编译器将为您分配内存,但事实并非如此。 You are trying to access an unallocated memory or you can dynamically allocate them using
malloc
or new
. 您正在尝试访问未分配的内存,或者可以使用
malloc
或new
动态分配它们。
More than that you can use std::string
to do get help from stl. 除此之外,您还可以使用
std::string
从stl获得帮助。
Either declare the str
like char str[fixed_size]
or use std::string. 可以像
char str[fixed_size]
这样声明str
或使用std :: string。 One of the simplest methods to do that might be this: 最简单的方法之一可能是:
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
string str;
cin >> str;
reverse(str.begin(),str.end());
cout <<str<< endl;
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.