gpt4 book ai didi

c - malloc() 是否在循环中重用相同的内存地址?

转载 作者:行者123 更新时间:2023-12-01 23:05:52 26 4
gpt4 key购买 nike

我开始学习 C 编程,偶然发现了一种情况,表明我对使用 malloc() 进行内存分配的工作原理缺乏了解。

在如下循环中:

// will only know `xlen` at runtime so I guess I have to use malloc here
char *x = malloc((xlen + 1) * sizeof(*x));
assert(x != NULL); // memory allocation failed

while (fgets(line, sizeof(line), fp) != NULL) {
strncpy(x, line, xlen); // copy first xlen characters of line
x[xlen] = '\0'; // ensure null terminating string

// do something with x
// x can now be "reused" for another line/loop iteration

// free(x) - errors out with "pointer being freed was not allocated"
}
fclose(fp)
free(x);

如果语句 free(x) 在循环内调用,那么当我运行这个程序时,我会收到类似 a.out(37575,0x7fff964ce3c0) malloc: ** * 对象 0x7fab47c02630 错误:未分配正在释放的指针

为什么我会看到这条错误消息,是什么原因导致的?

x 的内存地址 block 是否会在循环的每次迭代中被“重新使用”? (我会说是的,在这种情况下这实际上就是我想要的)在这种情况下,释放分配给 x 的内存是否安全?循环的范围?

最佳答案

free(x); 释放由 char *x = malloc(... 分配的内存。它释放所有内存,而你没有担心那是多少内存,因为它会跟踪它。你只需要调用 free(x); once 作为你正确的做法。这就是为什么你如果在循环内释放它,则会出现错误。

Does it mean that the memory address block of x will be "re-used" at each iteration? (I'd say yes, and that would actually be what I wanted in this case)

是的,你使用相同的内存。它每次都会覆盖内存。

In this case, is it safe to only free the allocated memory of x outside the loop scope?

是的,你必须在循环外释放它。因为如果你释放它,那么所有的东西都会被释放。如果您在循环内执行此操作,那么在后续循环迭代中继续访问该内存将是未定义的行为。

关于c - malloc() 是否在循环中重用相同的内存地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58628305/

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