gpt4 book ai didi

C free() 调用中的无效指针

转载 作者:太空宇宙 更新时间:2023-11-04 05:46:06 25 4
gpt4 key购买 nike

我正在编写一个函数,使用正则表达式在字符串中查找变量。该功能运行良好,但是当我尝试释放保存我正在评估的字符串的临时 char* 时,glibc 调用无效指针错误并且程序中止。在下面的代码中,如果从未进入 while 循环,则不会发生崩溃。

我做错了什么?

int parse_variables(size_t read_len)
{
regex_t comp_regex;
int start = 0;
char *command_copy = malloc(sizeof(command));
strcpy(command_copy, command);
if (regcomp(&comp_regex, "[$][^0-9_][A-Z0-9_]+", REG_EXTENDED) != 0)
{
pmesg(1, "Regex compilation failed. Not parsing for variables.\n");
return -1;
}
regmatch_t pmatch;
int var_match = regexec(&comp_regex, command_copy+start, comp_regex.re_nsub+1, &pmatch, 0);
pmesg(1, "The initial value of var_match is %i.\n", var_match);
while (var_match == 0) // We are finding instances matching the regex
{
int length = pmatch.rm_eo-pmatch.rm_so;
char* var_name = malloc(length*sizeof(char));
strncpy(var_name, command_copy + start + pmatch.rm_so, length);
pmesg(1, "The length is: %i - %i = %i.\n", pmatch.rm_eo, pmatch.rm_so, length);
pmesg(1, "The variable's name is: %s.\n", var_name);
free(var_name);
start += pmatch.rm_eo;
var_match = regexec(&comp_regex, command_copy+start, comp_regex.re_nsub+1, &pmatch, 0);
}
free(command_copy-start);
return 0;
}

最佳答案

您永远不会修改 command_copy,但您正试图在 command_copy-start 释放一个位置。

free(command_copy-start); 行更改为 free(command_copy);

它在从未进入循环时工作的原因是因为 start 永远不会从零开始改变。

关于C free() 调用中的无效指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4917701/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com