Memory allocation

K

krish

when we call realloc() the previous block of memory assigned through
calling malloc is copied into a new location and the re-allocation of
memory is done but the previous block of memory still remains..what
happens to this chunk of memory? Is it freed by the operating system?
 
P

Phlip

krish said:
when we call realloc() the previous block of memory assigned through
calling malloc is copied into a new location and the re-allocation of
memory is done but the previous block of memory still remains..what
happens to this chunk of memory? Is it freed by the operating system?

Your runtime library frees it. The reason you _don't_ free it is the
realloc() function might opt to grow your pointer's pointed-to memory
in-place, by claiming more of the unclaimed storage after it. So your own
code should not worry whether the pointer is really changed or not.

Now use std::vector<>, without an overwhelming and degenerate reason to use
realloc()!
 
J

Jack Klein

when we call realloc() the previous block of memory assigned through
calling malloc is copied into a new location and the re-allocation of
memory is done but the previous block of memory still remains.

Not necessarily. If there is sufficient room on the free store
directly following the original block, realloc() may just expand the
block in place, and not need to move or copy anything. And if it is
making the block smaller, it may leave it in the same place.
.what
happens to this chunk of memory? Is it freed by the operating system?

Actually, the C++ language does not specify that. The C++ language
standard is based on the C language standard as of 1995. Due to an
oversight, the original C standard does not say what happens to the
original block of memory if realloc() does need to move the contents.

This was corrected in the 1999 version of the C standard, which says
that if a successful realloc() moves the contents to a new block, the
old block is freed. But technically, this is not normative to the C++
standard.

In the real world, I am sure all C++ and C compilers, no matter what
version of their respective standard they conform to, free the old
block when realloc() moves the contents to a new one. The same as if
you called free() on the block.

That does not mean that the memory is returned to the operating
system, and in fact most implementations do not do that, merely keep
it available for a further call to malloc(), calloc(), or realloc().
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,596
Members
45,143
Latest member
SterlingLa
Top