C++ 使用堆栈时,分段错误是什么?如何修复?
我正在写一个程序来检查括号的分数,Leetcode问题856。然而,在我使用的算法中,我遇到了一个“分段错误(核心转储)”错误。我不确定在使用堆栈时如何出现分段错误,以及如何修复它C++ 使用堆栈时,分段错误是什么?如何修复?,c++,c++11,C++,C++11,我正在写一个程序来检查括号的分数,Leetcode问题856。然而,在我使用的算法中,我遇到了一个“分段错误(核心转储)”错误。我不确定在使用堆栈时如何出现分段错误,以及如何修复它 string s; cin >> s; int score = 0; stack<int> st; for (int i = 0; i < s.size(); i++){ char a = s[i]; if (a == '('){
string s;
cin >> s;
int score = 0;
stack<int> st;
for (int i = 0; i < s.size(); i++){
char a = s[i];
if (a == '('){
st.push(score);
score = 0;
}
else{
score = st.top() + max(score*2, 1);
st.pop();
}
}
cout << score;
}
字符串s;
cin>>s;
智力得分=0;
斯塔克街;
对于(int i=0;i cout当堆栈为空且您尝试.top()或.pop()时,它将给出分段错误(由访问内存引起的错误)
字符串s;
cin>>s;
智力得分=0;
斯塔克街;
对于(int i=0;i cout当程序试图访问超出数组大小界限的内存位置时,会发生分段错误。
要解决此问题,您必须检查是否正在访问大小为0到sizeOfArray-1的阵列
您可以使用if或while条件来检查此问题。这取决于您的程序试图实现的目标。我们也可以在不使用堆栈的情况下解决此问题:
// The following block might slightly improve the execution time;
// Can be removed;
static const auto __optimize__ = []() {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
std::cout.tie(nullptr);
return 0;
}();
// Most of headers are already included;
// Can be removed;
#include <cstdint>
#include <string>
static const struct Solution {
using ValueType = std::uint_fast16_t;
static const int scoreOfParentheses(
const std::string S
) {
ValueType scores = 0;
ValueType level = 0;
for (ValueType index = 0; index < std::size(S); ++index) {
if (S[index] == '(') {
++level;
} else {
--level;
}
if (S[index] == ')' && S[index - 1] == '(') {
scores += 1 << level;
}
}
return scores;
}
};
//下面的块可能会稍微缩短执行时间;
//可以移除;
静态常数自动优化{
std::ios::与stdio同步(false);
标准:cin.tie(无PTR);
标准::cout.tie(无PTR);
返回0;
}();
//大多数标题已经包含在内;
//可以移除;
#包括
#包括
静态常数结构解{
使用ValueType=std::uint\u fast16\u t;
Parenthesis的静态常数int分数(
常量std::字符串S
) {
ValueType得分=0;
ValueType级别=0;
对于(ValueType索引=0;索引<标准::大小;++索引){
如果(S[索引]=='('){
++水平;
}否则{
--水平;
}
如果(S[index]==')'和&S[index-1]=='('){
分数+=1当第一个字符不是(
?什么是st.top())时,代码中会发生什么
在这种情况下?在调用堆栈的top
或pop
函数之前,必须始终检查堆栈是否为空。它延迟了无效指针,并且与堆栈没有任何关系。segfault不一定会发生。任何其他情况都可能发生。在emp上调用top
ty堆栈是未定义的行为
// The following block might slightly improve the execution time;
// Can be removed;
static const auto __optimize__ = []() {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
std::cout.tie(nullptr);
return 0;
}();
// Most of headers are already included;
// Can be removed;
#include <cstdint>
#include <string>
static const struct Solution {
using ValueType = std::uint_fast16_t;
static const int scoreOfParentheses(
const std::string S
) {
ValueType scores = 0;
ValueType level = 0;
for (ValueType index = 0; index < std::size(S); ++index) {
if (S[index] == '(') {
++level;
} else {
--level;
}
if (S[index] == ')' && S[index - 1] == '(') {
scores += 1 << level;
}
}
return scores;
}
};