c中的动态内存释放问题

Dynamic memory deallocating issue in c

这是我的代码:

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

int *mem(void){

  //int buf[]= {1,1,2,3};
  int *buf = malloc(2 * sizeof(int));
  buf[1] = 1;

  return buf;
  free(buf);
}

int main(void){

  int *a[1] = { &mem()[1] };
    
  printf("%d", *a[0]};
  free(a[0]);
  return 0;

}

输出为 1,正如预期的那样,但当我在 Valgrind 中检查时,出现内存泄漏,显示 3 次分配和 2 次释放。我不想在这里使用 static

谁能帮我解决这个问题?

内存泄漏在这里应该不是什么大问题。您的程序正在调用未定义的行为,因为您正在释放尚未 mallocd.

的内存

将这两行添加到您的程序中以查看程序的运行情况:

printf("Returning %p\n", buf);
return buf;

printf("%d at %p\n", *a[0], a[0]);
free(a[0]);

输出应该是这样的:

Returning 0x602000000010
1 at 0x602000000014

并且在对 free 的下一次调用中,地址 0x602000000014 被传入其中 而不是 mem() 中分配的内存. freed 的内存与由于 int 的大小而分配的内存之间存在完整的 4 字节差异在我的(可能是你的)系统上,即 &buf[0]&buf[1] 相差 4 个字节。

将您的程序更改为

int *a[1] = { &mem()[0] }; //point to the 0-th index of the returned buffer
printf("%d", a[0][1]); //get the 1-st index of the array pointed to by the a[0] pointer

要有正确的行为。另外,还有一件事。 return 之后的语句不会被执行。 free(buf)mem() 中是多余的。

编辑:这是 运行 valgrind 进行更改后的输出:

$valgrind --leak-check=full --show-leak-kinds=all  --track-origins=yes  --verbose  ./test

==3497== HEAP SUMMARY:
==3497==     in use at exit: 0 bytes in 0 blocks
==3497==   total heap usage: 2 allocs, 2 frees, 520 bytes allocated
==3497==
==3497== All heap blocks were freed -- no leaks are possible
==3497==
==3497== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)