Jacob Sharf
Jacob Sharf

Reputation: 250

C realloc segmentation fault with appending char * to char **

I'm having trouble with the following code, which appends a char * to a char** by allocating more space.

size_t appendToken(char *tokens[], char *token, size_t size, size_t cap)
{
    if(size>=cap)
    {
        cap+=512;
        tokens = realloc(tokens, cap*sizeof(char *));
    }
    tokens[size] = token;
    return cap;
}

I get a segmentation fault when this code executes and size = cap (if there is remaining capacity, it behaves as expected). I've traced everything else, and it all behaves as expected. here is how tokens and token are initiated:

size_t tokenCount=0, tokens_cap = 5;
char **tokens = malloc(tokens_cap*sizeof(char *));
size_t size = 0;
size_t capacity = 4;
char *token = malloc(capacity*sizeof(char));

and here is how the function is called:

token_cap = appendToken(tokens, token, tokenCount++, token_cap);

I'd greatly appreciate some help with this.

Upvotes: 1

Views: 431

Answers (1)

Olaf Dietsche
Olaf Dietsche

Reputation: 74028

You need an additional indirection for the tokens parameter

size_t appendToken(char ***tokens, char *token, size_t size, size_t cap)
{
    if(size>=cap)
    {
        cap+=512;
        *tokens = realloc(*tokens, cap*sizeof(char *));
    }
    (*tokens)[size] = token;
    return cap;
}

Otherwise, the outside code would access the previously allocated, and now freed, memory.

You will then call this as

token_cap = appendToken(&tokens, token, tokenCount++, token_cap);

Upvotes: 1

Related Questions