[英]Segmentation fault when trying to read stdin to a 2d dynamically allocated array
I'm trying to read from stdin to a dynamic array of strings, using spaces as separators. 我正在尝试使用空格作为分隔符,从标准输入读取字符串的动态数组。 The code is as follows 代码如下
#include<stdio.h>
#include<stdlib.h>
char** parseInput(size_t *numElements)
{
char **lines;
int outerIndex = 0;
int innerIndex = 0;
int widths = 1;
char c=getchar();
lines =(char**) malloc((outerIndex+1)*sizeof(char*));
lines[0] = (char*) malloc(sizeof(char));
while(c!=EOF)
{
if(innerIndex==widths)//reallocate each strings length, double it
{
widths+=widths;
int i;
for(i=0;i<outerIndex+1;i++)
lines[i]=(char*)realloc(lines[i],(widths+1)*sizeof(char));
}
lines[outerIndex][innerIndex]=c;
innerIndex++;
if(c==' ')//allocate memory for the next string in the array of strings
{
lines[outerIndex][innerIndex]='\0';
innerIndex=0;
outerIndex++;
lines =(char**) realloc(lines,(outerIndex+1)*sizeof(char*));
lines[outerIndex] = (char*) realloc(lines[outerIndex],(widths+1)*sizeof(char));
//the above line in the debugger causes a segfault when outerIndex=19
}
c=getchar();
}
if(innerIndex!=0)//if the last character is not a space, append a space
{
if(innerIndex==widths)
{
widths+=widths;
int i;
for(i=0;i<outerIndex+1;i++)
lines[i]=(char*)realloc(lines[i],(widths+1)*sizeof(char));
}
lines[outerIndex][innerIndex]=' ';
lines[outerIndex][innerIndex+1]='\0';
}
*numElements=(size_t)(outerIndex+1);
return lines;
}
int main()
{
size_t num =0;
char** lines = parseInput(&num);
}
When the outer array size grows to anything more than 20 variables, I get a segmentation fault at the indicated line. 当外部数组的大小增加到超过20个变量时,在指定的行出现了分段错误。 For example the following input causes a segfault 例如,以下输入会导致段错误
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
but the following does not 但是以下不
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
The debug error says 调试错误说
Program received signal SIGSEGV, Segmentation fault.
0x0000003417e7bf4d in realloc () from /lib64/libc.so.6
What could this be caused by? 这可能是什么原因造成的?
On this line: 在这行上:
lines[outerIndex] = (char*) realloc(lines[outerIndex], (widths+1)*sizeof(char));
you supply an uninitialized pointer as the first argument to realloc
. 您提供一个未初始化的指针作为realloc
的第一个参数。 You should probably use malloc
here instead. 您可能应该在这里改用malloc
。
Other issues: 其他事宜:
char c
should be int c
(read the documentation for getchar
to see why). char c
应该是int c
(阅读getchar
文档以了解原因)。 lines[outerIndex][innerIndex]='\\0'
writes out of bounds. 如果输入以空格开头,则lines[outerIndex][innerIndex]='\\0'
超出范围。 if(innerIndex==widths)
is repeated twice in your code; 以if(innerIndex==widths)
开头的代码块在您的代码中重复了两次; it would be better to either make this a function, or restructure your code so there is not this repetition. 最好使它成为一个函数,或者重组您的代码,这样就避免了这种重复。 sizeof(char)
which is always 1
. 您可以通过删除多余的类型转换和多余的sizeof(char)
始终为1
乘法来简化malloc / realloc调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.