yak
yak

Reputation: 3940

Splitting string with delimiters in C - segmentation fault

I want to write a function that will split a string into a char array. I know that the result array will ALWAYS have only two elements - servername and serverport. I wrote this, but it gives me "Segmentation fault" after compilation:

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

char* splitString(char stringToSplit[])
{
    int i = 0;
    char serverinfo[2];
    char *tmp;
    tmp = strtok(stringToSplit, ":");
    while (tmp != NULL)
    {
        serverinfo[i] = tmp;
        tmp = strtok(NULL, ":");
        i++;
    }
    return serverinfo;
}

int main(int argc, char **argv)
{
    char st[] = "servername:1234";
    char *tab = splitString(st);

    printf("%s\n", tab[0]);
    printf("%s\n", tab[1]);

    return 0;
}

Upvotes: 1

Views: 931

Answers (1)

Daniel Fischer
Daniel Fischer

Reputation: 183978

char serverinfo[2];

allocates space for two chars, but you store char*s there, so make it

char* serverinfo[2];

But you return it from the function, however, the local variable doesn't exist anymore after the function returned, so you need to malloc it

char **serverinfo = malloc(2*sizeof *serverinfo);

and declare the function as

char **splitString(char stringToSplit[])

for the correct type.

Upvotes: 3

Related Questions