简体   繁体   English

C将char *附加到char **来重新分配分段错误

[英]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. 我在使用以下代码时遇到麻烦,该代码通过分配更多空间将char *追加到char **。

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). 当执行此代码并且size = cap时,我遇到了分段错误(如果有剩余容量,它的行为将与预期的一样)。 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 您需要tokens参数的其他间接方式

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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