C免费和结构

Lea*_*ppi 13 c free pointers data-structures

我的问题是关于C free()函数,用于释放先前使用malloc()分配的内存块.
如果我有一个结构数据类型由几个指针组成,每个指针指向不同的内存位置,如果我在结构上应用free()会对这些内存位置会发生什么?这些地点也会免费吗?或只是分配指针的内存块?

Shi*_*zou 23

不,他们不会被释放.你必须"手动"释放它们.malloc对结构的内容一无所知(它根本不知道它是一个结构体,从它的角度来看它只是一块"记忆").


Tom*_*Tom 9

如果你只释放结构,那么结构中指针所指向的内存将不会被释放(假设它是mallocd).你应该先释放它们.

您可以使用valgrind(如果可用)自己查看:

#include <stdlib.h>

struct resources{
   int * aint;
   double * adouble;
};                                                                              
int main(){

   int* someint = malloc(sizeof(int) * 1024);
   double* somedouble = malloc(sizeof(double)* 1024);

   struct resources *r  = malloc(sizeof(struct resources));

   r->aint = someint;
   r->adouble = somedouble;

   free (r);
   return 0;

}

$ gcc test_struct.c -o test
$ valgrind ./test
==9192== Memcheck, a memory error detector
==9192== Copyright (C) 2002-2009, and GNU GPL'd, by Julian Seward et al.
==9192== Using Valgrind-3.6.0.SVN-Debian and LibVEX; rerun with -h for copyright info
==9192== Command: ./test
==9192== 
==9192== 
==9192== HEAP SUMMARY:
==9192==     in use at exit: 12,288 bytes in 2 blocks
==9192==   total heap usage: 3 allocs, 1 frees, 12,296 bytes allocated
==9192== 
==9192== LEAK SUMMARY:
==9192==    definitely lost: 12,288 bytes in 2 blocks
==9192==    indirectly lost: 0 bytes in 0 blocks
==9192==      possibly lost: 0 bytes in 0 blocks
==9192==    still reachable: 0 bytes in 0 blocks
==9192==         suppressed: 0 bytes in 0 blocks
==9192== Rerun with --leak-check=full to see details of leaked memory
==9192== 
==9192== For counts of detected and suppressed errors, rerun with: -v
==9192== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 12 from 7)
Run Code Online (Sandbox Code Playgroud)