Yoink Yoink - 16 days ago 11
C Question

Segfault in parsing char* into tokens

I'm trying to parse a string around an arbitrary index. In my simplest test program I could come up with I have an input string I read the input into and then do memcpy to parse the string.

For testing this I am typing in "this text" as input. readInput is a function where I just have it calling getline(&input, &size, stdnin) and return the input pointer.

int main(){
char *input;
input = readInput();

int parseAround = 4;
char *token1;
char *token2;

memcpy(token1, inputBuffer, 4);
printf("token: %s\n", token1); //prints "this"

memcpy(token1, inputBuffer + (parseAround+1), 4);
//when changed to memcpy(token2,...); segfaults
printf("token: %s\n", token1); //prints "text"


free(input);
return 0;
}


However when I change the second memcpy to use token2 rather than token1, I get a segmentation fault. Why is this?

Answer

You most likely need to allocate memory for token1.

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

int main(){
    char *input = NULL;

    size_t len = 0;
    ssize_t read;

    /* Read in the line "Hello world" */
    read = getline(&input, &len, stdin);
    printf("Retrieved line of length %zu :\n", read);
    printf("%s", input);

    /* Allocate memory for both parts of the string */
    char *token1 = malloc((read+1) * sizeof(char *));
    char *token2 = malloc((read+1) * sizeof(char *));

    memcpy(token1, input, 6);
    printf("token: %s\n", token1); //prints "Hello"

    memcpy(token2, (input+6), 5);
    printf("token: %s\n", token2); //prints "world"

    free(input);
    return 0;
}

Read in the line, allocate memory for each string part, and then copy the part you want into your s