分配超过需要

时间:2017-01-19 01:36:01

标签: c

我编写了一个代码,它分配了一个缓冲区,用于分配文件的内容。通过valgrind运行代码给了我这个

总堆使用量:9个分配,7个释放,10,905个字节分配

如果我没有弄错,代码只会分配3次,而且我会在需要时进行定位。

void read_from_file (const char* filename, size_t length, char* buffer)
{
  /* put your code here */
  FILE* fOpen;

  buffer = (char*)malloc(length+1);
  fOpen = fopen(filename, "r");

  if(!buffer) // --- Failed to allocate
    printf("Failed to allocate...\n");

  else if(!fOpen){ // --- Failed to open file
    free(buffer);
    fprintf(stdout, "Failed to read %s\n", filename);
    buffer = NULL;
  }

  else if(fgets(buffer, length+1, fOpen)!=NULL){ // Buffer has been copied
    fprintf(stdout, "buff is: %s\n", buffer);
    free(buffer);
    buffer = NULL;
  }
  else{ // --- Failed to copy correctly
    fprintf(stdout, "Failed to copy %s file...\n", filename);
    free(buffer);
    buffer = NULL;
  }
}

void main (int argc, char **argv)
{
  char* buff = NULL;

  read_from_file("test1.txt",10,buff);
  read_from_file("test2.txt",10,buff);
  read_from_file("test3.txt",10,buff);

}

1 个答案:

答案 0 :(得分:1)

它看起来没有内存泄漏,但您还没有关闭您打开的文件。这是Valgrind报告中“仍可到达”块的来源。从fclose(fOpen)函数返回之前只需read_from_file()

此外,main()的返回类型为int,而不是void。这是您更新的代码:

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

void read_from_file (const char* filename, size_t length, char* buffer)
{
  /* put your code here */
  FILE* fOpen;

  buffer = malloc(length+1);
  fOpen = fopen(filename, "r");

  if(!buffer) // --- Failed to allocate
    printf("Failed to allocate...\n");

  else if(!fOpen){ // --- Failed to open file
    free(buffer);
    fprintf(stdout, "Failed to read %s\n", filename);
    buffer = NULL;
  }

  else if(fgets(buffer, length+1, fOpen)!=NULL){ // Buffer has been copied
    fprintf(stdout, "buff is: %s\n", buffer);
    free(buffer);
    buffer = NULL;
  }
  else{ // --- Failed to copy correctly
    fprintf(stdout, "Failed to copy %s file...\n", filename);
    free(buffer);
    buffer = NULL;
  }

  if (fclose(fOpen) != 0) {
      fprintf(stderr, "Unable to close file");
  }
}

int main (void)
{
  char* buff = NULL;

  read_from_file("test1.txt",10,buff);
  read_from_file("test2.txt",10,buff);
  read_from_file("test3.txt",10,buff);

  return 0;
}

Valgrind的输出:

==3564== HEAP SUMMARY:
==3564==     in use at exit: 0 bytes in 0 blocks
==3564==   total heap usage: 6 allocs, 6 frees, 1,737 bytes allocated
==3564== 
==3564== All heap blocks were freed -- no leaks are possible
==3564== 
==3564== For counts of detected and suppressed errors, rerun with: -v
==3564== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)