seg faulting textbuffer newTB

时间:2017-12-11 14:20:37

标签: c linked-list segmentation-fault

当我运行我的程序时,它似乎在某处出现了分段错误,但是我已经运行了测试,似乎我无法找到它的位置。我正在使用gcc -Wall -Werror -std = c99 -O来编译。

任务是在TB newTB中创建一个用“\ n”分隔的文本缓冲区,并将其放在一个链表中。

test = newTB("hello\ngood bye\nworld\n");
[hello]->[good bye]->[world]

这是目前唯一的功能所以它必须是我错过的导致它出错的东西。

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

1 个答案:

答案 0 :(得分:0)

问题在于strtok功能。 如本文所述:
C's strtok() and read only string literals
strtok函数不适用于字符串文字,因为它会更改字符串 试试吧:

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