【发布时间】:2016-04-01 16:18:09
【问题描述】:
这基本上是我想要做的:
使用双指针在不同范围内分配的空闲内存。 以下代码不完整,但完全描述了我要执行的操作。
这是我读取缓冲区的函数(C 伪代码)
char *read_buffer(char *buf, myStruct **arr, int nbElm)
{
buf = malloc(...);
...//many things done (use of the read(),close()... functions
...//but not referencing any of the buffer to my structure
...
*arr = (myStruct *) = malloc(sizeof(myStruct) * nbElm);
return (buf);
}
这是我在内存分配和释放尝试之间使用的那种函数:
void using_struct(myStruct *ar, int nbElm)
{
int i;
i = 0;
while (i < nbElm)
{
// Here I use my struct with no problems
// I can even retrieve its datas in the main scope
// not memory is allocated to it.
}
}
我的主要功能:
int main(void)
{
char *buf;
myStruct *arStruct;
int nbElm = 4;
buf = read_buffer(buf, &arStruct, nbElm);
using_struct(arStruct, nbElm);
free(buf);
buf = NULL;
free(arStruct);
while(1)
{;}
return (1);
}
唯一的问题是我将 while 循环放在空闲函数之前或之后,使用 top 看不到任何内存变化 在我的终端上。 这正常吗?
提前致谢,
【问题讨论】:
-
你应该只
freeasStruct一次而不是循环。
标签: c pointers memory malloc free