gpt4 book ai didi

c - 内存泄漏 - C

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

在同一个文件中我有两个例程。第一个将存储来自一个文件的一些字节。另一个会将此信息提供给将处理该信息的例程。

boolean
adin_memory(char* buffer, int size_chunck, int end_flag){
real_data=(SP16 *)malloc(size_chunck); //real_data -->global
memcpy(&(real_data[0]),&(buffer[0]),size_chunck);

pos_write += size_chunck;
global_size = size_chunck;
global_end_flag = end_flag;
//end_flag = 1 --> end of Stream
//end_flag = 0 --> Streaming
return TRUE;
}

为了防止泄漏的可能性,我使用了 malloc。但是这个例程被调用了几次。所以,在 adin_memoryadin_read 的一些重复之后(free),我认为内存开始碎片化(我可以看到泄漏与任务管理器中输入文件的大小 - RAM 的增量)。是对的吗?我怎样才能防止这种情况发生?为了查看此泄漏,我在 adin_memory 的开头和结尾放置了一个断点,查看任务管理器。

int
adin_read(SP16 *buf, int sampnum)
{
FILE *fp;
int cnt = 0;
fp = gfp;

//(.......)
if(global_end_flag == 1 || pos_write == pos_read){ return -1;}

for(i = pos_read/sizeof(SP16); i <= sampnum; i++){
if(i >= pos_write/sizeof(SP16)) {
cnt = i;
//(....)
break;
}
buf[i] = real_data[i];
}
pos_write = 0;
//(....)
free(real_data);
return cnt;
}

最佳答案

int
adin_read(SP16 *buf, int sampnum)
{
FILE *fp;
int cnt = 0;
fp = gfp;

//(.......)
if(global_end_flag == 1 || pos_write == pos_read){
/* Leak is possibly here. You return without freeing.
Ensure free is called here also. And it is good practice to
make the freed pointer point to NULL so you can check and
avoid double free problems. */
return -1;
}

for(i = pos_read/sizeof(SP16); i <= sampnum; i++){
if(i >= pos_write/sizeof(SP16)) {
cnt = i;
//(....)
break;
}
buf[i] = real_data[i];
}
pos_write = 0;
//(....)
free(real_data);
return cnt;
}

关于c - 内存泄漏 - C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33374924/

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