[英]Segmentation fault when trying to read stdin to a 2d dynamically allocated array
我正在嘗試使用空格作為分隔符,從標准輸入讀取字符串的動態數組。 代碼如下
#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);
}
當外部數組的大小增加到超過20個變量時,在指定的行出現了分段錯誤。 例如,以下輸入會導致段錯誤
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
但是以下不
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
調試錯誤說
Program received signal SIGSEGV, Segmentation fault.
0x0000003417e7bf4d in realloc () from /lib64/libc.so.6
這可能是什么原因造成的?
在這行上:
lines[outerIndex] = (char*) realloc(lines[outerIndex], (widths+1)*sizeof(char));
您提供一個未初始化的指針作為realloc
的第一個參數。 您可能應該在這里改用malloc
。
其他事宜:
char c
應該是int c
(閱讀getchar
文檔以了解原因)。 lines[outerIndex][innerIndex]='\\0'
超出范圍。 if(innerIndex==widths)
開頭的代碼塊在您的代碼中重復了兩次; 最好使它成為一個函數,或者重組您的代碼,這樣就避免了這種重復。 sizeof(char)
始終為1
乘法來簡化malloc / realloc調用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.