0

공백을 구분 기호로 사용하여 문자열의 동적 배열로 stdin을 읽으려고합니다. 외부 배열 크기가 나는 표시 줄에서 세그먼트 오류를 ​​얻을 아무것도에 20 개 이상의 변수를 성장하면동적으로 할당 된 2 차원 배열에 stdin을 읽으 려 할 때 시멘트 오류가 발생했습니다.

#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); 
} 

을 다음과 같이 코드입니다. 예를 들어 다음과 같은 입력은 segfault의

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 

이가 무엇을 발생할 수 있습니다 말한다? 어떤 도움을 주시면 감사하겠습니다. 이 라인에

+0

죄송합니다. 필자는 붙여 넣기를하고, 컴파일하고, 실행했습니다.이 코드는 그대로이며 오류가 발생합니다. – cheesyfluff

+0

GDB를 사용하는 법을 배우는 것이 좋습니다. 괜찮은 링크 http://www.delorie.com/gnu/docs/gdb/gdb_toc.html – Chimera

답변

1

는 :

lines[outerIndex] = (char*) realloc(lines[outerIndex], (widths+1)*sizeof(char)); 

당신은 realloc에 첫 번째 인수로 초기화되지 않은 포인터를 제공합니다. 여기서는 malloc을 대신 사용해야합니다.

다른 문제 :

  • char cint c해야한다 (이유를 getchar에 대한 설명서를 참조).
  • 입력이 공백으로 시작하면 lines[outerIndex][innerIndex]='\0'은 범위를 벗어납니다.
  • if(innerIndex==widths)을 시작하는 코드 블록이 코드에서 두 번 반복됩니다. 이 함수를 만들거나 코드를 재구성하여이 반복이 없도록하는 것이 좋습니다.
  • 중복 캐스트를 제거하고 중복 곱셈을 sizeof(char) (항상 1)으로하여 malloc/realloc 호출을 단순화 할 수 있습니다.
  • malloc/realloc에서 오류가 발생했는지 확인하고 그에 따라 조치해야합니다.
+0

도 있습니다. 이와 같이 realloc을 호출하지 마십시오. 실패하면 원래 포인터를 잃어버린 것입니다. realloc의 결과를 임시 변수에 저장하고 성공시 할당하십시오. – bruceg

+0

[outerIndex] 행을 초기화 해 주셔서 감사합니다. = NULL; realloc 문 앞에는 오류를 수정하는 것으로 보입니다. – cheesyfluff