即使在手动释放内存后,valgrind 仍显示内存泄漏

valgrind shows memory leak even after manually freeing memory

C 专家,

我的主文件是 rchars.c 如下,

#include<stdio.h>
#include<stdlib.h>
#include "lib.h"
#include "markov.h"

int main () {
  int nc;
  printf("Enter number of characters: ");
  scanf("%d", &nc);

  struct Seq *eve = malloc(sizeof(struct Seq*) - sizeof(double)); // line 11

  eve = genSeq(nc);

  for(int i=0;i<nc;i++){
    printf("acor - %d: %f\n",i, *(eve->seq+i));
  };

  free(eve->seq); // freeing the seq pointer
  free(eve); // freeing the Seq structure

return 0;   
}

显然我正在用 free(eve->seq)free(eve) 占用 malloc 内存。但是,valgrind 分析表明 0 bytes in 1 blocks are definitely lost in loss record 1 of 1 如下:

...
...
==8783== 
==8783== HEAP SUMMARY:
==8783==     in use at exit: 0 bytes in 1 blocks
==8783==   total heap usage: 5 allocs, 4 frees, 2,084 bytes allocated
==8783== 
==8783== Searching for pointers to 1 not-freed blocks
==8783== Checked 76,336 bytes
==8783== 
==8783== 0 bytes in 1 blocks are definitely lost in loss record 1 of 1
==8783==    at 0x483977F: malloc (vg_replace_malloc.c:307)
==8783==    by 0x109870: main (rchars.c:11)
==8783== 
==8783== LEAK SUMMARY:
==8783==    definitely lost: 0 bytes in 1 blocks
==8783==    indirectly lost: 0 bytes in 0 blocks
==8783==      possibly lost: 0 bytes in 0 blocks
==8783==    still reachable: 0 bytes in 0 blocks
==8783==         suppressed: 0 bytes in 0 blocks
==8783== 
==8783== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)

即使按照规定释放内存后,我也无法确定泄漏实际发生的位置以及原因。虽然丢失的是0 bytes,但我对1 block感到困扰。我在这里缺少什么。我正在学习使用 C 的方法。任何 help/suggestion 来解决这个问题将不胜感激。

我的头文件有结构 Seq

...
struct Seq {
  int len;
  double *seq;
};
...

genSeq函数定义为

struct Seq *genSeq(int nc) {
  int i;
  // Struct assignment
  struct Seq *data = (struct Seq *)malloc(sizeof(int) + sizeof(double)*nc);
  double *seqn = (double *)malloc(sizeof(double) * nc);
  data->len = nc;
  if (seqn) {
    srand(time(NULL));
    for(i=0;i<nc;i++){
      //*(seqn+i) = sin(i+1);
      int j = rand();
      *(seqn+i) = (double)(j % 200);
      if (j % 3 == 0) {
        *(seqn+i) = (double)1.0;
      } else if (j % 2 == 0) {
        *(seqn+i) = (double)2.0;
      } else {
        *(seqn+i) = (double)3.0;
      }; 
      //printf("Signal: %f\n", *(seqn+i));
    }
  } else {
    printf("Null pointer returned: Sequence alloc failed\n");
  }
  data->seq = seqn;

  return data;
}

我读过这个valgrind shows memory leak even after memory free,但没有被接受的、令人信服的答案,对我没有太大帮助。

您正在从函数内部返回一个动态分配的结构,因此您不需要为其分配 more space。只需从 main:

中删除内存分配

替换为:struct Seq *eve = malloc(sizeof(struct Seq*) - sizeof(double));

struct Seq *eve = NULL;

Valgrind 通过告诉您您分配的比您应该分配的多,从字面上给了您答案:

total heap usage: 5 allocs, 4 frees, 2,084 bytes allocated

并且非常友好地与您分享了确切的位置,包括行号:

at 0x483977F: malloc (vg_replace_malloc.c:307)

现在,即使您想在 main 中为您的结构分配 space,您做错了,因为您为 struct Seq*(指向结构的指针)分配了足够的 space ) 而不是 struct Seq (具体结构)。