Search code examples
csegmentation-faultsegment

Three level indirection char pointer in C causes a segment fault


I got a segment fault error at the line with the comments that contains lots of equals signs below.

The function below str_spit, I wrote it because I want to split a string using a specific char, like a comma etc.

Please help.

 int str_split(char *a_str, const char delim, char *** result)
    {
       int word_length = 0;
       int cur_cursor = 0;
       int last_cursor = -1;
       int e_count = 0;
       *result = (char **)malloc(6 * sizeof(char *));
       char *char_element_pos = a_str;
       while (*char_element_pos != '\0') {
        if (*char_element_pos == delim) {
            char *temp_word =   malloc((word_length + 1) * sizeof(char));

            int i = 0;
            for (i = 0; i < word_length; i++) {
                temp_word[i] = a_str[last_cursor + 1 + i];
            }

            temp_word[word_length] = '\0';
            //
            *result[e_count] = temp_word;//==============this line goes wrong :(
            e_count++;
            last_cursor = cur_cursor;
            word_length = 0;
        }
        else {
            word_length++;
        }
        cur_cursor++;
        char_element_pos++;
    }
    char *temp_word = (char *) malloc((word_length + 1) * sizeof(char));
    int i = 0;
    for (i = 0; i < word_length; i++) {
        temp_word[i] = a_str[last_cursor + 1 + i];
    }
    temp_word[word_length] = '\0';
    *result[e_count] = temp_word;
    return e_count + 1;
  }

   //this is my caller function====================
  int teststr_split() {
    char delim = ',';
    char *testStr;
    testStr = (char *) "abc,cde,fgh,klj,asdfasd,3234,adfk,ad9";

    char **result;

    int length = str_split(testStr, delim, &result);
    if (length < 0) {
        printf("allocate memroy failed ,error code is:%d", length);
        exit(-1);
    }
      free(result);
      return 0;
    }

Solution

  • I think you mean

    ( *result )[e_count] = temp_word;//
    

    instead of

    *result[e_count] = temp_word;//
    

    These two expressions are equivalent only when e_count is equal to 0.:)