Realloc 内部函数未按预期工作

Realloc inside function doesn't work as expected

提问人:Stefano Carletto 提问时间:6/22/2023 最后编辑:BarmarStefano Carletto 更新时间:6/22/2023 访问量:49

问:

我正在开发一个程序,我成功地隔离了非工作部分,但我无法弄清楚为什么这不起作用。 函数内部的 realloc 应该重新分配数组元素,但有时地址相同,有时它们只是 0,这会导致代码内部出现错误并崩溃

int main() {
    char *string = (char*) malloc(sizeof(char));
    resizeString(&string);
    free(string)
    return 0;
}

void resizeString(char* *string) {
    int q;
    *string = realloc(*string, 5 * sizeof(char));
    for (q = 0; q < 5; q++) {
        printf("0x%p ", &*string[q]);
    }
    printf("\n");
}

this is the result of the printf inside the for loop

c malloc 动态内存分配 realloc

评论

3赞 Barmar 6/22/2023
请以文本形式发布代码、数据和结果,而不是屏幕截图(如何在帖子中设置代码格式)。为什么我不应该上传代码/数据/错误的图像? idownvotedbecau.se/imageofcode
0赞 yano 6/22/2023
不知道操作顺序是什么。如果要打印每个字符的地址,请尝试&*string[q]printf("%p ", (void*)((*string) + q));
0赞 user207421 6/22/2023
请参阅文档。有时,如果内存块可以原位扩展,则返回相同的值,如果内存不足,则返回 0。你需要测试这种情况,但你没有,所以当它返回 0 时,你会得到一个 SIGSEGV。
0赞 yano 6/22/2023
只是其他几件事 <O/T>,1) 确保使用 Temp PTR 正确重新分配以避免内存泄漏的可能性,以及 2) 了解这不会增加先前分配的空间,它只会分配指定的空间。因此,每次调用时,它不会为每个调用分配 5、10、15 等字节,每次只分配 5 个字节。reallocresizeString

答:

1赞 Jeremy Friesner 6/22/2023 #1

代码中的调用基本有效,但还有另外两个问题:realloc()

  1. 您的初始 one-char 分配永远不会初始化(因此不确定在调用之前或之后将包含哪个字符)realloc()

  2. 您打印出 post-realloc() 数组中字符的代码是错误的(它试图打印出指针,而不是字符,这没有意义)。

这是代码的更新版本,可以执行您期望的操作(请注意,我已将原始 char 初始化为 main() 中的 aka,以便我们可以验证在 realloc 发生后它是否仍设置为该值)X0x58

#include <string.h>
#include <stdio.h>
#include <stdlib.h>

void resizeString(char* *string) {
    int q;

    char * s = (char *) realloc(*string, 5 * sizeof(char));
    for (q = 0; q < 5; q++) {
        printf("0x%x ", s[q]);
    }
    printf("\n");

    *string = s;  // update calling code's pointer to the new buffer location
}

int main() {
   char *string = (char*) malloc(sizeof(char));
   *string = 'X';

   resizeString(&string);
   free(string);
   return 0;
}

...运行上述命令可得到以下输出:

0x58 0x0 0x0 0x0 0x0 
3赞 Barmar 6/22/2023 #2

您需要添加括号才能正确打印数组元素的地址。

        printf("%p ", &(*string)[q]);

这将正确打印连续的地址:

0x6000013dc040 0x6000013dc041 0x6000013dc042 0x6000013dc043 0x6000013dc044 

这与 无关,如果您最初分配了 5 个字符,您也会遇到同样的问题。realloc()

也不需要在格式字符串中写入;大多数 C 库会自动将该前缀显示为格式的一部分。0x%p

评论

0赞 Stefano Carletto 6/22/2023
所以这就是主代码中的问题:我没有写,而是,相反,我认为这导致了导致运算符优先级的意外行为,我没有以这种方式想到这一点......非常感谢你,现在我的代码运行没有问题!!(*string)[q]*string[q]