C将字符串分配给另一个字符串会导致realloc():下一个大小无效

问题描述 投票:-1回答:1

我正在尝试将一个结构中的字符串分配给另一个结构的字符串:

func->parameters[func->parameter_amount].name = tokens[i+1].value;

这在while循环中发生:

while (true) {
    func->parameter_amount++;
    func->parameters = realloc(func->parameters, func-> parameter_amount*sizeof(struct parameter));
    if (func->parameters == NULL) {
        mem_error();
    }
    if ((tokens[i].token != symbol) && (tokens[i].token != comma)) {
        break;
    } else if ((tokens[i].token == symbol) && tokens[i+1].token == symbol) {
        func->parameters[func->parameter_amount].type = string_to_type(tokens[i].value);
        if (func->parameters[func->parameter_amount].type == -1) {
            printf("Error: Invalid type '%s' for parameter declaration in function '%s' on line %i\n", tokens[i].value, func->name, func->line);
            exit(1);
        }
        func->parameters[func->parameter_amount].name = tokens[i+1].value;
        i += 2;
    } else if (tokens[i].token == comma) {
        func->parameter_amount--;
        i++;
    }
}

分配完成后,程序会说:realloc(): invalid next size并中止

结构定义为:

struct parameter {
    int type;
    char* name;
};

struct function {
    int line;
    int type;
    char* name;
    struct parameter* parameters;
    int parameter_amount;
};

typedef struct {
    int token;
    char* value;
    int line;
} token;

我不知道出了什么问题

c data-structures memory-management realloc
1个回答
1
投票

您的代码中存在多个错误:

1]在realloc之后,func->parameters数组的大小为func->parameterAmount。因此,这意味着最后一个索引可以使用func->parameterAmount-1

func->parameters[func->parameterAmount - 1]

2)对于func->parameters数组中的每个元素,您都必须分配字符串value(因为此时value只是一个指向字符的指针):

int i = 0;
int n = 129; // n will be the max length (minus 1) of newly allocated string
for (i = 0; i < func->parameterAmount; ++i) {
    func->parameters[i].name = (char *) malloc(sizeof(char) * n);
    if (func->parameters[i].name == NULL) {
      // Handle alloc error
    }
} 

此外,请记住在令牌value内分配所有字符串变量array

3)在C中,您不能以这种方式为字符串分配值。您必须使用strcpy()标头中的string.h

strcpy(func->parameters[func->parameter_amount].name, tokens[i+1].value);
© www.soinside.com 2019 - 2024. All rights reserved.