nookonee
nookonee

Reputation: 921

C - What does free() do to the memory?

I recoded malloc() free() and realloc().

I have a linked list with the pointers returned by malloc().

The question is : what does free() really do ?

Currently, I did a memset() to have the same behavior of free().

But was it better just to set a flag in my list as 'is free' rather than doing a memset() in order to make it faster ?

Upvotes: 3

Views: 12832

Answers (3)

PravinY
PravinY

Reputation: 530

Free : Call will unlink / unallocate the memory pointed by pointer so that other process can use it.

Memset : Call will set a memory / fill a memory location. It won't unlink / unallocate a memory and memory remain allocated / occupied till the program exist. Which can cause memory leaks.

You can use valgrind tool to check memory leaks.

And it is a better practice to unlink / unallocate a memory if its not required.

Upvotes: 4

Leonard Michlmayr
Leonard Michlmayr

Reputation: 365

Usually free(3) does not do anything to the memory itself. (If security or privacy is a concern, you should clear memory before freeing.)

If you want to implement malloc, you need to have some database of free memory blocks. When memory is freed you should join it with adjoint free memory, if there is any. If a complete page ends up unused, you should tell the kernel, that you don't need it anymore (depending on how you got that memory in the first place)

Upvotes: 3

KonK
KonK

Reputation: 290

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

You should use it to prevent memory leaks.

Upvotes: 2

Related Questions