valgrind即使手动释放内存也显示内存泄漏

问题描述 投票:0回答:1

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

显然,我正在用mallocfree(eve->seq)充值free(eve)存储器。但是,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的方法。对解决和解决此问题的任何帮助/建议将不胜感激。

我的头文件具有结构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,但没有被接受的令人信服的答案,对我没有太大帮助。

c memory-leaks valgrind
1个回答
0
投票

您正在从函数内部返回动态分配的结构,因此您无需为其分配more

© www.soinside.com 2019 - 2024. All rights reserved.