Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct usage of free() function in C

I am new in C programming language so can you tell me if this is correct way to do.

for example: program points on buffer and i use that pointer as parameter in free() function. So, what problems can this function cause ?

like image 866
DDeme Avatar asked Apr 04 '15 09:04

DDeme


People also ask

What is the use of free () in C?

C library function - free() The C library function void free(void *ptr) deallocates the memory previously allocated by a call to calloc, malloc, or realloc.

What is the use of free () function?

The free() function in C++ deallocates a block of memory previously allocated using calloc, malloc or realloc functions, making it available for further allocations. The free() function does not change the value of the pointer, that is it still points to the same memory location.

What is malloc () and free ()?

Dynamic memory allocation This helps us avoid running into insufficient memory and makes us use the memory space efficiently. In the C programming language, two of the functions used to allocate and deallocate the memory during run-time are malloc() and free() , respectively.


2 Answers

You should call free only on pointers which have been assigned memory returned by malloc, calloc, or realloc.

char* ptr = malloc(10); 

// use memory pointed by ptr 
// e.g., strcpy(ptr,"hello");

free(ptr); // free memory pointed by ptr when you don't need it anymore

Things to keep in mind:

  • Never free memory twice. This can happen for example if you call free on ptr twice and value of ptr wasn't changed since first call to free. Or you have two (or more) different pointers pointing to same memory: if you call free on one, you are not allowed to call free on other pointers now too.

  • When you free a pointer you are not even allowed to read its value; e.g., if (ptr) not allowed after freeing unless you initialize ptr to a new value

  • You should not dereference freed pointer

  • Passing null pointer to free is fine, no operation is performed.

like image 149
Giorgi Moniava Avatar answered Oct 06 '22 13:10

Giorgi Moniava


Think that the computer has a whole bunch of memory not (yet) used by your program. Now you need some more memory and you ask your computer to give you some more (for example, a large buffer). Once you are done with it, you want to return it to the computer.

This memory is called the heap. You ask for memory by calling malloc() and you return it by calling free();

char *buffer;
buffer = malloc(512);           // ask for 512 bytes of memory
if (buffer==NULL) return -1;   // if no more memory available
...
free(buffer);                 // return the memory again
like image 36
Paul Ogilvie Avatar answered Oct 06 '22 12:10

Paul Ogilvie