Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Having issues splitting strings when using the strsep function

I’m very new to C programming and was trying to split a string through it’s delimiters using the strsep function.

When executing the code below i get this output:

Hostname ( teste-13-f8-04teste-13-fd-80) Hostname (teste-13-fd-80) Hostname (teste-13-fd-86) Hostname (teste-13-fd-90)

Why is the AllHostName[0] giving that output?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

void splitStrings(char splitString[] , char variable[][15]);

void splitStrings(char splitString[] , char variable[][15])
    {
        char *token, *str, *tofree;
        int i=0;
        tofree = str = strdup(splitString);
        while ((token = strsep(&str, ",")))
            {
                strcpy(variable[i], token);
                i++;
            }
    free(tofree);
    }

int main(){
            char HostName[] = " teste-13-f8-04,teste-13-fd-80,teste-13-fd-86,teste-13-fd-90";
            char AllHostName[32][15];
            splitStrings(HostName, AllHostName);
            printf(" Hostname (%s) Hostname (%s) Hostname (%s) Hostname (%s)\n" , AllHostName[0] , AllHostName[1],AllHostName[2],AllHostName[3]);
           }

After getting this error I’ve noticed that it’s related to the size of the original string, if it’s a smaller string this issue doesn’t appear.

>Solution :

The first token in

char HostName[] = " teste-13-f8-04,teste-13-fd-80,teste-13-fd-86,teste-13-fd-90";

is

teste-13-f8-04

which is 15 characters long and too long for the 16 character token (which includes a terminating '\0' character) to fit into any of the 15-character elements of char variable[][15].

The terminating '\0' character gets overwritten by the first character of the next token, causing the tokens to run together.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading