segfault appending a empty string C

I am trying to append a string with a specific char. I am getting a segfault from what I believe is because i am trying to append to a memory address and I dont know how i would go about changing this.

Here is the error that is shown when I am debugging,

print: 6

word to be appended: ����Z�����H���E

Segmentation fault (core dumped)

This is the code corresponding to the segfault

void append(char* s, char c){

        printf("print: 5\n");
        int len = strlen(s);

        printf("print: 6\n");
        printf("word to be appended: %s\n", s);
        s[len] = c;

        printf("print: 7\n");
        s[len+1] = '\0';

This is the call for the above function is at the bottom of this set of code with the corresponding variable initialization

    int x;
    char *tempLine = NULL;
    char *token = NULL;
    char *punctuationChar;
    size_t length = 0;
    int charCount = 0;
    char *word;
    int i;
    int p;
    int check = 0;
    struct node *curr = NULL;
    struct node *newNode = NULL;

    (*head) = malloc(sizeof(struct node));   
    curr = (*head);     


    for(x = 0; x < size; x++){

            getline(&tempLine, &length, stream);
            token = strtok(tempLine, " ");
            if(x == 0){

                    charCount = strlen(token);
                    curr -> word = malloc(charCount *(sizeof (char)) + 1);
                    strcpy(curr -> word, token);
                    token = strtok(NULL, " ");


            while(token != "\n"){

                    check = 0;
                    printf("token: %s\n", token);
                    charCount = strlen(token);
                    printf("print: 1\n");

                    //check for punctuation aka, last word on line
                    for(i = 0; i < charCount; i++){
                            printf("iteration: %d\n", x);

                                    printf("print: 2\n");
                                    append(punctuationChar, token[i]);
                                    check = 1;

1 answer

  • answered 2018-04-17 06:00 Stephan Lechner

    You call append(punctuationChar, token[i]), yet punctionatChar has not been initialized. This yields undefined behaviour.

    To overcome this, let punctuationChar point to a properly allocated memory space, that is initialized with a valid string, i.e. one with a string termination character;

    To try it out you could simple start with:

    char tempBuffer[100] = "something to start with";
    char* punctationChar = tempBuffer;

    This will not solve probable issues in your program flow; but it should show up the root cause of your issue.