bmpasini
bmpasini

Reputation: 1503

strsep() doesn't work as expected

strsep is not parsing my string correctly. I used " " as a delimiter, and it is parsing the string in the middle of a word. I can't figure out why.

Code:

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


#define BUFFERSIZE 128
#define BLANK_STR " "

static char *inputs[BUFFERSIZE];

void prepare_inputs(char *input){
    int i = 0;
    char *token;

    while ((token = strsep(&input,BLANK_STR)) != NULL) {
        printf("token: %s\n", token);
        if (inputs[i] == NULL)
            inputs[i] = calloc(strlen(token) + 1, sizeof(char));
        else {
            memset(inputs[i], 0, strlen(inputs[i]));
        }
        strncat(inputs[i], token, strlen(token));
        printf("inputs[i]: %s\n", inputs[i]);
        i++;
    }
}


int main(void) {
    char *input = calloc(BUFFERSIZE, sizeof(char));

    while(1) {
        fgets(input, sizeof(input), stdin);
        prepare_inputs(input);
    }
}

Input:

hi hii hiii hiiii

Output:

token: hi
inputs[i]: hi
token: hii
inputs[i]: hii
token:
inputs[i]:
token: hiii
inputs[i]: hiii
token: hi
inputs[i]: hi
token: iii

inputs[i]: iii

Upvotes: 1

Views: 639

Answers (1)

user4812626
user4812626

Reputation:

sizeof does not give you the size of a dynamically-allocated memory block. It gives you the size of the pointer.

Upvotes: 3

Related Questions