2017-12-11 15 views
0

내 프로그램을 실행할 때 테스트가 실행되었지만 어디에서나 찾을 수없는 것처럼 보이는 부분 분할 오류가있는 것 같습니다. 컴파일 할 때 gcc -Wall -Werror -std = c99 -O를 사용하고 있습니다.seg faulting textbuffer newTB

"\ n"으로 구분하고 링크 된 목록에 넣는 TB newTB에 텍스트 버퍼를 만드는 작업입니다.

현재 현재로서는이 기능이 유일하기 때문에 내가 놓친 부분이있어 세그 폴트가 발생합니다.

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 

#include "textbuffer.h" 

struct textbuffer { 
    char *text; 
    int length; 
    TB next; 
}; 

void printBuffer(TB tb); 

TB newTB (char text[]){ 
    if (text == NULL) { 
     printf("buffer underflow\n"); 
     abort(); 
    } 

    TB new = calloc(1, sizeof(struct textbuffer)); 
    new->length = 0; 
    new->next = NULL; 
    TB current = new; 

    char *token; 
    int size; 

    //first token; intialise first. 
    token = strtok(text, "\n"); 
    size = strlen(token); 
    current->text = calloc(size + 1, sizeof(char)); 
    strcpy(current->text, token); 
    //use memset to add a NULL terminator at the end. 
    memset(current->text, '\0', size + 1); 
    new->length++; 
    current->next = NULL; 



    int count = 0; 
    while (token != NULL) { 
     //first linked list already done, do nothing for the first loop. 
     if (count == 0) { 

     } else { 
      //create next textbuffer and fill it with the token. 
      current->next = calloc(1, sizeof(struct textbuffer)); 
      current = current->next; 
      size = strlen(token); 
      current->text = calloc(size + 1, sizeof(char)); 
      strcpy(current->text, token); 
      memset(current->text, '\0', size + 1); 

      new->length++; 
     } 

     count++; 
     token = strtok(NULL, "\n"); 
    } 

    current->next = NULL; 


    return new; 
} 
+0

사용'이 대신 calloc''의 malloc'. –

+1

'memset (current-> text, '\ 0', size + 1);은 전체 문자열을 0으로 설정합니다. 네가 원하는게 아니야. 그것을 제거 할 수 있습니다.'strcpy'는 이미 그것을합니다 (나는'strdup'를 사용했습니다). –

+1

디버그 버전을 빌드하고 (빌드 할 때'-O' 플래그를 버리고'-g' 플래그를 추가하십시오), [ 귀하의 프로그램을 디버깅] (https://ericlippert.com/2014/03/05/how-to-debug-small-programs/). –

답변

0

문제는 strtok 함수에 있습니다. 이 게시물에 설명 된대로 :
C's strtok() and read only string literals
strtok 함수는 문자열을 변경하기 때문에 문자열 리터럴에 대해 작동하지 않습니다.
그냥 시도 : 어쨌든 그것을 초기화하고 같은

char str[] = "hello\ngood bye\nworld\n"; 
test = newTB(str);