Search code examples
cfunctionsegmentation-faultmallocrealloc

C - dynamical allocation/rellocation inside the function


I have written this function in C (function should receive a char*, allocate space necessary, and insert character given a pointer to the index of character behind the pointer)

void add_to_str(char *character, char ** string, int* index)
{
    //we dont expect  *string to be NULL !! no condition done
    if (*index == 0)    //if str is empty we will alloc AVGLEN(32) characters space
       *string=malloc(AVGLEN*sizeof(char));

    if (*string == NULL)   //malloc fails?
    {
        fprintf(stderr,errors[MALLOC]);
        exit(99);
    }
    //string length exceeds 32 characters we will allocate more space
    if ( *index > (AVGLEN-1) || character== NULL )// or string buffering ended, we will free redundant space
    {
        *string=realloc(*string,sizeof(char)*((*index)+2));//+1 == '\0' & +1 bcs we index from 0
        if (*string==NULL)   //realloc fails?
        {
            fprintf(stderr,errors[REALLOC]);
            exit(99);
        }
    }
    *string[(*index)++]=*character;
}

When *index > 0, it gives me a segmentation fault on the line

*string[(*index)++]=*character;

A variant of this function (just malloc behind char* and then assign characters to string[i++]) works perfectly.


Solution

  • You have to be careful with this statement:

    *string[(*index)++]=*character;
    

    Because array indexing has higher precedence than pointer dereferencing. Thus, this is the same as

    *(string[(*index)++]) = *character;
    

    Which is not what you want. You want this:

    (*string)[(*index)++] = *character;
    

    The faulty code works for *index == 0 because in that case the statement is equivalent to **string, which is still valid, but when index > 0, string is going to be dereferenced in an invalid position: string+index.