记忆泄漏 - C

时间:2015-10-27 17:40:48

标签: c memory-leaks

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

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;
}

4 个答案:

答案 0 :(得分:2)

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;
}

答案 1 :(得分:1)

很难说没有进一步描述你如何使用这些功能的上下文,但是......

每次调用adin_memory()函数时,它都会分配一些内存(通过调用malloc),然后将real_data设置为指向新分配的内存。

如果real_data已经指向某个已分配的内存,那么你就泄露了它。

因此,如果你的主程序调用{​​{1}}三次,然后调用adin_memory(),那么你将泄漏两块内存,只释放最后一块。

答案 2 :(得分:0)

更改

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

if(global_end_flag == 1 || pos_write == pos_read)
{
    free(real_data);
    return -1;
}

答案 3 :(得分:0)

问题确实存在于连续的malloc / free中(导致内存碎片)。删除后,我创建一个指向传入字节的全局指针。并在memcpy

中制作adin_read()
int adin_read(SP16 *buf, int sampnum)
{
    int i;
    int cnt = 0; 
    if(global_end_flag == 1 || pos_write == pos_read){return -1}
    memcpy(buf,global_buffer,global_size);
    cnt = global_size/sizeof(SP16);
    pos_write = 0;
    pos_read = 0; 
    //(....) 
    return cnt;
}

然后:

boolean
adin_memory(char* buffer, int size_chunck, int end_flag){
    pos_write += size_chunck;
    global_size = size_chunck;
    global_end_flag = end_flag;
    global_buffer = buffer;
    return TRUE;
}
相关问题