I have a problem with splitting a string in C. Every time I try to execute my code I get a 'segmentation fault' error. But I don't quite know what the problem is.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char** string_array = NULL; //string array for the split method
static int split_string(char* string, char* delimiter)
{
char* part = strtok(string, delimiter);//string which is getting split out by strtok
int number_of_parts = 0;//number of strings
/*split string into multiple parts*/
while(part)
{
string_array = realloc(string_array, sizeof(char*)* ++number_of_parts);
if(string_array == NULL)//allocation failed
return -1;
string_array[number_of_parts-1] = part;
part = strtok(NULL, delimiter);
}
/*write final null into string_array*/
string_array = realloc(string_array, sizeof(char*)* (number_of_parts+1));
string_array[number_of_parts] = 0;
return 0;
}
int main()
{
char* string = "string1 string2 string3";
printf("%d", split_string(string, " "));
return 0;
}