分段错误取决于字符串长度? [英] Segmentation fault depending on string length?

查看:76
本文介绍了分段错误取决于字符串长度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个程序,该程序将使用getline将infile中的行读取为字符串,然后将字符串转换为包含字符串的前m个非空白字符的c字符串,然后将c字符串连接到单个char数组中./p>

示例文件可能如下所示:

5    //number of rows and columns in a grid
2    //number of grids
XXXXX
XXXXX
XXXXX
XXXXX
XXXXX

XXXXX
XXXXX
XXXXX
XXXXX
XXXXX

所以我最终得到一个2x5x5字符的char数组. 现在的问题是,我的代码在较小的测试用例(如上图所示)中可以正常工作,但是当我在较大的网格(即100x100x100)上尝试时,分段错误.

#include <iostream>
#include <string>
using namespace std;
int main(){
  int mapsize,levels;
  cin>>mapsize;
  cin>>levels;
  char map[mapsize*mapsize*levels];
  string input;
  for (int i=0;i<levels;i++){
    for (int j=0;j<mapsize;j++){
      getline(cin,input);
      char *row;
      row=new char[input.size()+1];
      strcpy(row, input.c_str());
      for (int k=0;k<mapsize;k++){
        map[i*mapsize*mapsize+j*mapsize+k]=row[k];
      }
      delete [] row;
    }
  }
return 0;
}

我将用一个infile调用该程序: ./程序< infile.in

我已经使用gdb运行它并进行了回溯. 它始终指向字符串输入"行.

有什么想法可以解决此段错误吗? 谢谢

解决方案

map是在堆栈上分配的VLA,所以我想您的问题是堆栈溢出. gdb指出了input的构造,因为这是在此溢出堆栈上构造的第一件事.

I am writing a program that will read lines from an infile using getline into strings, convert the strings to c-strings containing the first m nonwhitespace characters of the string, then concatenate the c-strings into a single char array.

A sample file might look something like this:

5    //number of rows and columns in a grid
2    //number of grids
XXXXX
XXXXX
XXXXX
XXXXX
XXXXX

XXXXX
XXXXX
XXXXX
XXXXX
XXXXX

So I'd end up with a char array of 2x5x5 characters. Now the problem is my code works fine on smaller test cases like the one shown above, but segmentation faults when I try it on bigger grids (i.e. 100x100x100).

#include <iostream>
#include <string>
using namespace std;
int main(){
  int mapsize,levels;
  cin>>mapsize;
  cin>>levels;
  char map[mapsize*mapsize*levels];
  string input;
  for (int i=0;i<levels;i++){
    for (int j=0;j<mapsize;j++){
      getline(cin,input);
      char *row;
      row=new char[input.size()+1];
      strcpy(row, input.c_str());
      for (int k=0;k<mapsize;k++){
        map[i*mapsize*mapsize+j*mapsize+k]=row[k];
      }
      delete [] row;
    }
  }
return 0;
}

I'd call this program with an infile: ./program < infile.in

I've run it using gdb and did backtrace. It always points to the line "string input;"

Any ideas how I can resolve this segfault? Thanks

解决方案

map is a VLA, allocated on the stack, so I'd guess that your problem is that you get a stack overflow. gdb points a the construction of input because that's the first thing that gets constructed on this overflowed stack.

这篇关于分段错误取决于字符串长度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆