分段错误取决于字符串长度?
我正在编写一个程序,它将使用 getline 从 infile 读取行并将其转换为字符串,将字符串转换为包含字符串的前 m 个非空白字符的 c 字符串,然后将 c 字符串连接成单个 char 数组。
示例文件可能如下所示:
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 运行它并进行了回溯。 它始终指向“字符串输入;”行
我有什么想法可以解决这个段错误吗? 谢谢
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
map
是一个VLA,在堆栈上分配,所以我猜你的问题是堆栈溢出。 gdb 指向input
的构造,因为这是在这个溢出的堆栈上构造的第一个东西。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 ofinput
because that's the first thing that gets constructed on this overflowed stack.我不确定为什么回溯指向
string input;
但当您将row
复制到map
时。如果mapsize大于行的大小,你很可能会出现段错误。对于较大的地图尺寸,这种情况更为常见。您也可能会踩踏堆栈上的返回地址,这可能会导致“错误”的核心转储。
I am not sure why the backtrace is pointing to
string input;
but when you are copyingrow
intomap
. if mapsize is bigger than the size of row, you could well end up seg-faulting. This will be more common for a bigger mapsize.you also may well be stomping over return addresses on the stack that could be causing the "wrong" core-dump.