0

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;
}
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
blub
  • 115
  • 1
  • 4
  • @n.m. agreed but difficult for the OP to find this reference. – Jean-François Fabre Oct 22 '16 at 15:56
  • Note that the `old_ptr = realloc(old_ptr, new_size)` construct leaks memory if/when the reallocation fails. You need to use `void *new_ptr = realloc(old_ptr, new_size); if (new_ptr == 0) { …handle error… } old_ptr = new_ptr;`. That way, you still have a valid pointer in `old_ptr` that can still be freed. – Jonathan Leffler Oct 22 '16 at 15:58

1 Answers1

2

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.

Bjorn A.
  • 1,148
  • 9
  • 12
  • there's also another problem: the `strtok` part needs `strdup` or you get the same string in all pointers. – Jean-François Fabre Oct 22 '16 at 15:55
  • Just for the record: The gcc compiler option -Wwrite-strings warns for this kind of problem. For some weird reason, this warning has been removed from -Wdiscarded-qualifiers, and is not a part of -Wall -Wextra -std=c99 -pedantic. Weird. – Bjorn A. Oct 22 '16 at 16:07
  • that's just stupid!! I found the problem manually, and used -Wall without success. Is there a link on SO which explains how to get all the warnings, I mean all the warnings? thx for the info. Maybe you should edit your answer to add this info. – Jean-François Fabre Oct 22 '16 at 16:09