简体   繁体   English

Segmentation Fault(Core Dumped)

[英]Segmentation Fault (Core Dumped)

At Line 40 my code stops running and outputs signal: segmentation fault(cored dumped), and I am confused to why my code is segmentation faulting since i am not accessing any index out of bounds nor am I modifying a string literal.在第 40 行,我的代码停止运行并输出信号:分段错误(核心转储),我很困惑为什么我的代码是分段错误,因为我没有越界访问任何索引,也没有修改字符串文字。 Baiscally, If the value (k + i) is greater than N, i want to iterate backwards until there is a spot "." Baiscally,如果值 (k + i) 大于 N,我想向后迭代直到有一个点“。” in array(patches) to place either a patch "H" or "G".在数组(补丁)中放置补丁“H”或“G”。

Here is the the input i am taking in: 1 5 4 GHHGG这是我正在接受的输入:1 5 4 GHHGG

Here is the code I wrote:这是我写的代码:

#include <iostream>
#include <vector>
#include <array>
using namespace std;
int main() {
string cows;
int CONST_N = 100000;
array<string, 100000> patches;
int t, n, k, patchCounter{}; cin >> t;
  while(t--){ 
    patchCounter = 0;
    cin >> n; cin >> k;
    cin >> cows;
  //  cout << n << endl;
    for(int i = 0 ;i < CONST_N;i++){
  patches[i] = "N";
}
    for(int i = 0 ;i < n ;i++){
      patches[i] = ".";
    }
    for(int i = 0; i < n ;i++){
      if(cows.substr(i, 1) == "G"){
        if(patches[k + i] == "N"){
          for(int j = n - 1; j >=0;j++){
            if(patches[j] == "."){
              patches[j] = "G";
              break;
            }
        }
          } else {
          patches[k+i] = "G"; i+=(2*k); patchCounter++; 
          }
        }
      }
    for(int i = 0; i < n ;i++){
      if(cows.substr(i,1) == "H"){
         // cout<<(patches[k +i]  == "N") << endl;
        //cout << patches[k +i] << endl;
         if(patches[k + i] == "N"){
           cout << "hello";
          for(int j = n - 1; j >=0;j++){
            if(patches[j] == "."){
              patches[j] = "H";
              break;
            }
        }
          } else {
          patches[k+i] = "H"; i+=(2*k); patchCounter++; 
          }
        }
      }
    cout << patchCounter << endl;
    for(int i = 0 ;i < n ;i++){
      cout << patches[i];
    }
    cout << endl;
 
    }
  return 0;
}

I was unsure what to do since array size is 10^5 and i am only accessing index 6 so i am very confused what's happening.我不确定该怎么做,因为数组大小是 10^5,而且我只访问索引 6,所以我很困惑发生了什么。 I would really appreciate some help.我真的很感激一些帮助。 Thanks!谢谢!

Your code seems to have a typo, here您的代码似乎有错字,在这里

for (int j = n - 1; j >= 0; j++) {
    if (patches[j] == ".") {
        patches[j] = "H";
        break;
    }
}

should be应该

for (int j = n - 1; j >= 0; j--) { // TYPO -- not ++
    if (patches[j] == ".") {
        patches[j] = "H";
        break;
    }
}

Honestly this took me 30 seconds to discover with a debugger.老实说,这花了我 30 秒才用调试器发现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM