Freeing C Functions

In C, which is best practice when it comes to freeing the memory returned from functions:

  • Provide a destructor function that encapsulates the call in free ().
  • Require users of a free () returned pointer.

For example, to open and close a file, we do:

FILE* f = fopen("blah", "w");
fclose(f);

This is preferable:

FILE* f = fopen("blah", "w");
fclose(f);
free(f);

Warning: Do not call free () in the FILE pointer. I use it only in a hypothetical implementation.

What about cases where local variables are referenced in returned memory? Is free () harmful here? (or perhaps this should never be done)

FILE f = &fopen("blah", "w");
fclose(&f);
+5
source share
10 answers

- fclose , . , , malloc. .

, , :

, , .

1) , , . * - - free(f); ...

2) DLL, , , , , Windows. DLL, VS2005 VS2008, , , . "" .

3) API C , FILE *, fopen/fclose. .

+10

. .. , . API (callle), API .

/ :

int * mymem = (int *)malloc(20 * sizeof(int));
...
a_func_to_call(mymem);
...
free(mymem);

/ :

FILE* f = fopen("blah", "w"); // allocs a FILE struct
fclose(f); // The implementation of fclose() will do what necessary to 
           // free resources and if it chooses to deallocate any memory
           // previously allocated
+14

FILE *, malloc.
- .

+5

FILE* f FILE, , . free(f), malloc().

fclose , , .

: , , .

wrapperFree(Pointer* p)
{
 //do some additional work [ other cleanup operations ]
 free(p);
}

, , WrapperFree WrapperAllocate .

, , thumbrule malloc() free() .

+2

fopen FILE C, ( free d) fclose.

0

, malloc(), fopen(). malloc() . free().

0

mgb, free() a FILE *. , . :

  • "", - free . FILE * - : , .
  • free(), . - .
0

...

, , , , .

open/allocate , / .

FILE * .

0

, " " (.. /), , , , /

, , atexit(), , .

0
source

I not only love the functions of the destructor, but also as a Dave Hanson convention, which takes the address of the pointer and resets the pointer as the memory becomes free:

Thing_T *Thing_new(void);
void Thing_dispose(Thing_T **p);   // free *p and set *p = NULL
0
source

All Articles