Question

I wrote a function split for c++, because i need it in my program, but it randomly crashes the program. If i keep restarting the same sample program, it sometimes works, sometimes it crashes.

Here is the function:

char ** split(char * string, char delimiter, int &num_substrings)
{
num_substrings = 0;

char ** substrings = NULL;
int temp_len = 0;
int string_pos = 0;


substrings = (char **) calloc(1, sizeof(char*));
substrings[num_substrings] = (char *) calloc(1, sizeof(char));

while(string[string_pos] != '\0')
{
    if(string[string_pos] == delimiter)
    {
        num_substrings++;
        substrings = (char **) realloc(substrings, (num_substrings + 1) * sizeof(char*));
        substrings[num_substrings] = (char *) calloc(1, sizeof(char));
        temp_len = 0;
    }else{
        substrings[num_substrings] = (char *) realloc(substrings[num_substrings], (temp_len + 1) * sizeof(char));

        substrings[num_substrings][temp_len] = string[string_pos];
        temp_len++;
        substrings[num_substrings][temp_len] = '\0';
    }
    string_pos++;
}


return substrings;

}

And here is how i tested it (the main function):

int main()
{
char *s = "1|3|teststring|";
char ** args = NULL;
int num = 0;

args = split(s, '|', num);
cout<<num<<"\n";
cout<<args[0];

}

I am compiling it with codeblocks, but with microsoft visual studio is the same result.

Was it helpful?

Solution

To answer the question with the function as-is, temp_len+1 is not large enough because you increment temp_len in this code:

      substrings[num_substrings] = (char *) realloc(substrings[num_substrings],
           (temp_len + 1) * sizeof(char)); // Allocation here
      // ...
      temp_len++;
      substrings[num_substrings][temp_len] = '\0'; // Invalid write 1 byte after

But I concur with using std::string or std::vector.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top