gpt4 book ai didi

c - 字符串重新分配的意外行为

转载 作者:行者123 更新时间:2023-12-04 10:56:55 25 4
gpt4 key购买 nike

我遇到了使用字符串函数进行内存分配的奇怪行为。

备注 : 现在我被告知忽略分配操作的失败。

我的代码是:

void string_reallocation(char *result, int result_length) {
char *temp_result = malloc((strlen(result) + 1) * sizeof(char));

strcpy(temp_result, result);

realloc(result, (result_length + 1) * sizeof(char));

strcpy(result, temp_result);

free(temp_result);
}

在 while 循环中通过迭代调用此函数:
    while (current_node != NULL) {
current_value_to_string = current_node->toStringFunc(current_node->value);
current_value_length = (int) strlen(current_value_to_string);
current_length += current_value_length + arrow_length;

string_reallocation(result, current_length);

strcat(result, current_value_to_string);
strcat(result, arrow);

current_node = current_node->next;
}
current_node是 Node 类型,如下所示:
typedef struct t_node {
Element value;
struct t_node *next;
elementDestroy destroyFunc;
elementCopy copyFunc;
elementToString toStringFunc;
} *Node;

事情是,出于某种原因,特别是在第三次迭代中, free(temp_result);因段错误而失败。

我不认为while循环与段错误有任何关系,但我把它放在这里以防万一。

最佳答案

这是一个双相解决方案,因为您必须了解如何使用 realloc() ,通过检查其原型(prototype)。让我们先这样做。

改变这个:

realloc(result, (result_length + 1) * sizeof(char));

对此:
result = realloc(result, (result_length + 1) * sizeof(char));

reference ,我们得到了这个方法的原型(prototype):

Return value: A pointer to the reallocated memory block, which may be either the same as ptr or a new location.



现在,考虑一下变量(指针)的范围。正如@whozCraig 评论的那样, result = (在更正后的 realloc() 中)将值分配给自动变量。在调用方传递的原始结果没有改变,现在悬空。这必须使用输入/输出参数或函数返回结果来处理。

所以你可以做的就是简单地返回那个指针,通过改变这个:
void string_reallocation(char *result, int result_length) {

对此:
char* string_reallocation(char *result, int result_length) {
// ...
return result;
}

然后将对此函数的调用更改为:
result = string_reallocation(result, current_length);

关于c - 字符串重新分配的意外行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59111109/

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