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?
#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.
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.