Ukani Sandipkumar
Ukani Sandipkumar

Reputation: 31

When malloc function allocate same memory location?

I have calling malloc function at various place in my bsm_create function but in some the place where I have got same memory address. Can malloc/calloc function freed some location and again allocate that location in linux(fedora) environment.

Upvotes: 2

Views: 1677

Answers (3)

a3.14_Infinity
a3.14_Infinity

Reputation: 5843

  • When malloc function allocate same memory location?
    • When you invoke malloc function, you are requesting to give some space in heap. If the requested space is present, malloc gives the starting address of the allocated space. Let's call it A. A is the starting address of the allocated space.
    • When we invoke free on this allocated space, we are requesting to deallocate, so now this returned space is free to be used by the runtime. So, memory starting at location A with allocated bytes is deallocated and returned to runtime.
    • So, when someone asks for some space again, there is a great possibility ( and probability!=0) that some bytes starting at memory address A is still free, so the runtime could give A back again.

Hope it helps!

Upvotes: 2

hexasoft
hexasoft

Reputation: 677

You did not explicitly indicate if you freed them. As said by others a freed memory area can be reused, but of course you will not get same address if still allocated.

But if you reallocate (realloc() and familly) with a higher size it can be moved elsewhere so the initial address can/may be reused later, even without freeing anything.

Example: allocating 32*sizeof(int) two times gives the addresses: 0xeee010 0xeee0a0

Reallocating the 1st one to 64*sizeof(int) lead to a new address: 0xeee130

Then allocating an other 32*sizeof(int) fall on the 1st address: 0xeee010

Upvotes: 0

mah
mah

Reputation: 39807

When a buffer previously allocated with malloc() (or its family) has been released with free() (or indirectly released in a realloc() call), it will be reused - which means you can expect it to be returned in a future allocation. This is the reason you want to free() in the first place.

Upvotes: 5

Related Questions