gpt4 book ai didi

c - 尝试将标准输入读取到二维动态分配的数组时出现段错误

转载 作者:行者123 更新时间:2023-11-30 15:00:39 25 4
gpt4 key购买 nike

我正在尝试从标准输入读取到动态字符串数组,使用空格作为分隔符。代码如下

#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 调用。
  • 您应该检查 malloc/realloc 是否失败并采取相应措施。

关于c - 尝试将标准输入读取到二维动态分配的数组时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41990269/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com