C 崩溃分段故障:11

C++ crash Segmentation fault: 11

本文关键字:故障 分段 崩溃      更新时间:2023-10-16

我一直在研究一个程序,以测试一些字符串操纵的可能性。它基本上应该读取字符串列表,并能够找到角色的邻居作为电路。这是代码:

    #include <iostream>
    #include <string>
    #include <sstream>
    #include <fstream>
    std::string grid[20]={" "};
    std::string get(int string, int member){
      return grid[string].substr(member,1);
    }
    std::string* getNeighbors(int string, int member){
      std::string neighbors[4];
      neighbors[0]=grid[string-1].substr(member,1);//up
      neighbors[1]=grid[string+1].substr(member,1);//down
      neighbors[2]=grid[string].substr(member-1,1);//left
      neighbors[3]=grid[string].substr(member+1,1);//right
      std::string* p=neighbors;
      return p;//Returns up,down,left,right.
    }
    int main(int argc, char** argv){
      grid[1]="@----^---0";
      grid[2]="abcdefghi0";
      grid[3]="jklmnopqr0";//TODO Change to read of txt*/
      std::string* neighbors;
      for(int i=0;grid[1].length()>i;i++){
        neighbors=getNeighbors(2,1);
        if(neighbors[3]=="-" | neighbors[3]=="^"){
          std::string r=get(1,i);
          (r!="0") ? std::cout<<r:0;//Dangerous. TODO Unknown symbol handling
          std::cout<<neighbors[3];
        }
      }
    }

这很好地编译了,但是具有运行时错误"分段故障:11"。我正在使用我不习惯的几个科目和技术,可能会滥用。任何帮助都会很棒。

std::string neighbors[4];已分配。当您出门getNeighbors时,它会松开范围。尝试将其放置在另一个地方(甚至是全球性的概念证明)。更好的设计应该通过该功能来通过。

void getNeighbors(int string, int member, std::vector<std::string>& neighbors){
      ;
      neighbors[0]=grid[string-1].substr(member,1);//up
      neighbors[1]=grid[string+1].substr(member,1);//down
      neighbors[2]=grid[string].substr(member-1,1);//left
      neighbors[3]=grid[string].substr(member+1,1);//right
    }

编辑:

#include <iostream>
    #include <string>
    #include <sstream>
    #include <fstream>
    std::string grid[20]={" "};
    std::string neighbors[4]; //<---------------------------
    std::string get(int string, int member){
      return grid[string].substr(member,1);
    }
    std::string* getNeighbors(int string, int member){
      neighbors[0]=grid[string-1].substr(member,1);//up
      neighbors[1]=grid[string+1].substr(member,1);//down
      neighbors[2]=grid[string].substr(member-1,1);//left
      neighbors[3]=grid[string].substr(member+1,1);//right
      std::string* p=neighbors;
      return p;//Returns up,down,left,right.
    }
    int main(int argc, char** argv){
      grid[1]="@----^---0";
      grid[2]="abcdefghi0";
      grid[3]="jklmnopqr0";//TODO Change to read of txt*/
      std::string* neighbors;
      for(int i=0;grid[1].length()>i;i++){
        neighbors=getNeighbors(2,1);
        if(neighbors[3]=="-" | neighbors[3]=="^"){
          std::string r=get(1,i);
          (r!="0") ? std::cout<<r:"0";//Dangerous. TODO Unknown symbol handling
          std::cout<<neighbors[3];
        }
      }
    }

neighbors现在是全局的(我不喜欢这样,但要为POC做工作)。

getneighbors()正在将指针返回到本地变量。