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

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 ?

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.

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)

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.

Related

calling malloc function does't always call sbrk function internally?

I'm new to C and heap memory, below is my understanding about dynamic memory allocation, please correct me if I'm wrong:
Fact 1-When the first time calling malloc, malloc will call sbrk internally to move/grow the brk pointer(program break).
Fact 2-after calling malloc and free a couple of times, there could be free blocks between two allocated blocks, so if we call malloc again with a required size less than the size of free blocks, then this time malloc will not call sbrk internally, instead, malloc just modify one existing free block's structure(setting allocated bit ...etc) and return the address of this block.
There is nothing in the standard that says malloc() must move/grow the brk pointer to allocate memory. In fact, nowadays malloc() will often use mmap(..., MAP_ANONYMOUS, ...) internally to obtain memory.
It is likely that if there is a gap after repeated malloc() and free() calls, that the next malloc() might be able to allocate memory in the gap, such that no calls to sbrk() or mmap() are necessary. But again, there is no guarantee that this will actually happen.

Increase heap size of a running process

I'm new to linux programming and i want to know is it possible to increase the heap size of a running process. If it is possible, please help me how to do it right. Thanks anyone for helping.
Heap is just memory. There is nothing special about it. Any memory can become heap. Diagrams showing a heap area are pedagogical, rather than real.
"Heap" is is "Heap" only because the memory is allocated by a heap manager. While most programs only have on heap manager, it is possible to have multiple heap managers.
Thus heap size is controlled by a heap manager. Most simple heap managers give the user no control over the heap size. The heap manager allocates more memory when it needs memory to respond to allocation calls.
Some heap managers give the user function calls to allow him to allocate an expand the heap size.
Just use a function like malloc() or calloc() to allocate memory dynamically. To deallocate the memory and return it to the heap, use free(). These functions will manage the size of the heap by expanding or shrinking it as needed.
Example:
Everything in heap is anonymous. You can't access the memory directly. Every access is indirect. So store the address of allocated memory returned by malloc() in a pointer.
int *ptr = malloc(sizeof(int));
We can use *ptr to access the memory's contents.
*ptr = 3;
printf("%d", *ptr);
Once you are done using the memory. You deallocate it with
free(ptr);
According to Peter van der Linden's book on C programming,
The end of the heap is marked by a pointer known as the "break". When the heap manager needs more memory, it can push the break further away using the system calls brk and sbrk.
You typically don't call brk yourself explicitly, but if you malloc enough memory, brk will eventually be called for you.
Your program may not call both malloc() and brk(). If you use malloc, malloc expects to have sole control over when brk and sbrk are called.
The limit on the maximum size of heap is determined by the size of virtual memory of the system.
Here's a crude reproduction of the image:

Will malloc automatically free the memory at the end of a function?

I would be very glad if someone could help me in understanding completely the differences between the following codes:
// Code (1)
void f1 ( void ){
int * ptr1 = malloc ( sizeof(int) );
}
and
// Code (2)
void f2 ( void ){
int * ptr2 = malloc ( sizeof(int) );
free(ptr2);
}
As far I know, the instruction free is useful for deallocating the used memory, but on the other hand I know that every time we call a function g, if here there are new variables to be declared, they will be created and destroyed (i.e. deallocated, right?) after the execution of g.
Consequently:
do we need to use the instruction free in Code(2), or it is superfluous? (but maybe suggested for making the code more clear)
Thanks
Ps: you may be also interested in helping me with My previous related question. There, some users suggested to use the dynamic allocation of memory, and I am trying to understand why/how to.
No. malloc will not free the allocated memory. You need to use free to free the allocated chunk.
It is also the case that at the end of the program (main function) the allocated memory automatically freed by the system, but better to free it explicitly.
Always remember that the lifetime of dynamically allocated memory is till the end of the program if it is not deallocated specifically.
As said previously, memory allocated by malloc should be unallocated by free, or else you'll get memory leaks. What confuses you is that the ptr1var itself is unallocated (not the memory it's pointing to). The allocated memory is not a variable. So when you exit f1, you have no way to access your allocated memory any more, as you've lost the address.
BTW you've not explained why you need new addresses in your previous question.
No, you have to use free (or realloc)
From http://www.cplusplus.com/reference/cstdlib/malloc/:
If the function reuses the same unit of storage released by a deallocation function (such as free or realloc), the functions are synchronized in such a way that the deallocation happens entirely before the next allocation.
More information: How do malloc() and free() work?
No, malloc() will not release the memory when the function terminates.
If I may offer a suggestion though ...
If you want to allocate space (for a (very) small object) only throughout a (non-recursive) function you can use C99's variable length arrays
int foobar(size_t small_n) {
struct whatever autorelease[small_n]; // C99 VLA
// use autorelease
// no need to free
return 0;
} // memory for autorelease object released
In addition to other answers explaining about C dynamic memory allocation and the need to explicitly call free for each malloc-ed data (and when to call free is an issue; you want to avoid memory leaks), and you'll find a tool like valgrind helpful, you could also consider using Boehm's garbage collector. You basically could replace malloc by GC_malloc in your entire program and not bother a lot about explicit free-ing.
Of course, read the wikipage on garbage collection, and later the
GC handbook. It does have some caveats. So Boehm's GC is not a silver bullet.

How are we able to access the pointer after deallocating the memory?

As per my understanding,
free() is used to deallocate the memory that we allocated using malloc before.
In my following snippet, I have freed the memory i have allocated. But i was able to access the pointer even after freeing? How it is possible?
How free works internally?
#include<iostream>
using namespace std;
int main()
{
int *p=(int *)malloc(sizeof(int));
*p=17;
free(p);
*p=*p+1;
printf("\n After freeing memory :: %d ",*p );
return 0;
}
You can certainly continue to use p after calling free(p) and nothing will stop you. However the results will be completely undefined and unpredictable. It works by luck only. This is a common programming error called "use after free" which works in many programs for literally years without "problems" -- until it causes a problem.
There are tools which are quite good at finding such errors, such as Valgrind.
Accessing a dangling pointer will result in undefined behavior.
A dangling pointer is the one which is already freed.
After free(p), p is a dangling pointer which points to no where. free() just releases the memory block allocated by malloc() and it doesn't change the value of pointer pointing to heap in that process address space. On some platforms you might get segfault if you try dereferencing pointer after freeing. Its good practice if you assign pointer p to NULL after freeing.
In most systems and standard libraries, malloc is optimized by allocating a larger chunk of memory than required (up to 64K on some systems) from the OS, and then internally disbursing it as per requirement from this pool. The same applied to the deallocation (free) as well, in that, the free'd memory isn't freed, but put back in the memory pool, in case another request comes in, in which case the pool is reused.
Thus, the call to free hasn't actually freed the memory from the process's address space and is thus accessible even after free.
My understanding as to why this is done is that system calls are expensive, so the initial call to malloc will make a system call for enough memory that future requests for malloc do not immediately trigger another system call for more memory.
As for further reading, please take a look at this page on Wikipedia, How do malloc() and free() work? and How is malloc() implemented internally?

free() not freeing up memory properly?

I'm trying to free up the memory I've allocated with malloc, but the free command doesn't seem to do its job properly according to Eclipse's debugger. How's this possible?
Below is a screenshot of my debugger after it supposedly freed up seCurrent->student->year, which is clearly not the case. year was allocated using malloc.
alt text http://img693.imageshack.us/img693/7840/codeo.png
free() does not normally change any values in your program - it just makes adjustments to the C runtime heap. This means that the values in the memory that was just freed are retained. However, attempts to access them from your code lead to undefined behaviour.
What makes you think it hasn't freed it? Freeing memory means that accessing it from the program thereafter is undefined behavior, and the memory is available for re-use next time you call malloc. It does not promise to overwrite the data that was stored in the memory you freed, or to prevent the debugger from reading the unallocated memory.
Free will return the allocated space to the heap to be reused by subsequent mallocs but it does not change the values of any pointers that previously referenced that memory. In your case, no other mallocs have yet been performed so the memory just freed is still the same as it was just prior to the call to free. In order for your code to know that there is no longer any data associated with the pointer, you may want to set it to null after freeing the memory associated with it.
when you malloc() some memory, all it does is searching for some free space in memory, and keeping track it is now used. It doesn't initialize it or whatever.
when you call free(), all it does is clearing this memory block out of the list of used memory blocks. Again it doesn't modify the contents.

Resources