zzuussee zzuussee - 1 year ago 63
C Question

C - split string into multiple parts

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*/
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;

Answer Source

strtok() writes to the string, so you cannot use a string literal as argument. The problematic line is this one:

char* string = "string1 string2 string3";

A possible fix is to change string from pointer to array:

char string[] = "string1 string2 string3";

The gcc compiler option -Wwrite-strings warns for this kind of problem.

Note that this warning has been removed from gcc's option -Wdiscarded-qualifiers, and will not be enabled by e.g. -Wall -Wextra -std=c99 -pedantic.