seg faulting textbuffer newTB


when I run my program, it seems to have a segmentation fault somewhere however I’ve run tests and it seems I cannot find where it is. I’m using gcc -Wall -Werror -std=c99 -O to compile.

The task is to create a textbuffer in TB newTB that separates by “\n” and puts it in a linked list.

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

This is currently the only function at the moment so it has to be something I’ve missed that’s causing it to seg fault.

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

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


        token = strtok(NULL, "\n");

    current->next = NULL;

    return new;


memset(current->text, '\0', size + 1); sets the entire string to zero. Not what you want. You can remove that, strcpy does it already (I’d have used strdup)
Also you’re strcpying a string then overwriting it with zeroes with memset… perhaps step back and figure out what this code ought to do for real…
Build a debug version (drop the -O flag and add the -g flag when building), and learn how to debug your programs.
A string is always terminated by \0. Otherwise it’s not a string. As strcpy copies strings, it must copy including \0. It doesn’t “add” it. It is already there in the source string and is copied.
What is “TB”? Some icky typedef hiding a pointer?