I have a small snippet. It is related with several malloc statements. Can somebody please explain.

#include <stdio.h>
#include <stdlib.h>

int main(){
    char* ptr1 = (char*)malloc(10);
    free(ptr1);
    char* ptr2 = (char*)malloc(10);
    free(ptr1);
    char* ptr3 = (char*)malloc(10);
    free(ptr1);
return 0;
}

What will happen to the snippet..? Will the malloc for ptr2 or ptr3 will allocate the same memory that has been freed by free(ptr1)..

More importantly what will happen internally if I free a memory which is already freed.

Will the malloc for ptr2 or ptr3 will allocate the same memory that has been freed by free(ptr1)..

Maybe, maybe not. It really depends on the memory manager malloc uses for that specific implementation. I wouldn't make that assumption though.

what will happen internally if I free a memory which is already freed.

Well, given that the block of memory no longer exists as far as the memory manager is concerned, bad things will happen. Officially, you invoke undefined behavior. In practice, you'll be looking at crashes, memory corruption, and potentially an unwanted release of a reused block.

If you free an already freed memory block, usually your program with crash with a SEGFAULT error. As deceptikon said, you cannot be guaranteed that reallocation of a block after freeing another, even if it is of the same size, will return the same block of memory. A lot of allocators will use a LRU (Least Recently Used) algorithm when getting memory out of the available pool. They will also try to merge adjacent freed blocks for bigger allocations to succeed without asking the operating system for more heap space. This is a complex subject. I spent several years working on memory allocators for Unix back when, including reference counting allocators (assign a pointer to multiple entities will increase the reference count and freeing one instance will just decrement the count until the count gets to zero, when the allocator will return the memory to the pool).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.