简体   繁体   中英

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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM