【问题标题】:C assigning string to another string results in realloc(): invalid next sizeC将字符串分配给另一个字符串会导致realloc():下一个大小无效
【发布时间】:2020-04-07 06:22:07
【问题描述】:

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

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;

我不知道出了什么问题

【问题讨论】:

  • 分配指针不会复制内存块。如果这指向动态分配的内存,则需要确保在不使用任何指针之前不会释放它。如果您不这样做,您将取消引用已释放的指针,并导致未定义的行为。
  • 你应该使用func->parameters[func->parameter_amount].name = strdup(tokens[i+1].value);
  • 我们真的需要minimal verifiable example,因为根本原因可能在也可能不在您显示的代码中。但这看起来很可疑:func->parameters[func->parameter_amount]func->parameter_amount 设置的确切值是多少?如果它是参数的数量,那么最大数组索引将为parameter_amount-1。使用parameter_amount会导致缓冲区溢出。

标签: c data-structures memory-management realloc


【解决方案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
    }
} 

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-13
    • 1970-01-01
    • 2020-12-24
    • 2020-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多