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

C assigning string to another string results in realloc(): invalid next size

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

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;

我不知道出了什么问题

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

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 inside token array.

3) 在 C 语言中,您不能以这种方式为字符串赋值。您必须使用 strcpy() from string.h header:

strcpy(func->parameters[func->parameter_amount].name, tokens[i+1].value);