473,796 Members | 2,460 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

realloc() implicit free() ?

If realloc() finds it necessary to move the memory block, then
does it free() the previously allocated block?

The C89 standard has some reference to undefined behaviour if one
realloc()'s memory that was freed by realloc(), but the only way
explicitly mentioned in the C89 standard to free memory via realloc()
is to realloc() it down to 0 bytes.

I had always assumed it would automatically free the previous memory,
but is the behaviour instead undefined [or defined as not happening] ?
--
"This was a Golden Age, a time of high adventure, rich living and
hard dying... but nobody thought so." -- Alfred Bester, TSMD
Nov 14 '05
86 4175
Dave Vandervies wrote:
.... snip ...
The draft I have describes realloc's behavior as "changes the size
of the object pointed to by ptr" (4.10.3.4; I believe this is the
ANSI numbering but I'm not certain - it's the draft that came from
Dan Pop's collection). If it's changing the size and not creating
a new one, there's no old one left behind for you to free.


Does anyone know what happened to Dan? Just before he disappeared
he seemed to be looking for a new position, and then he showed up
momentarily from Switzerland. He added a great deal here,
including insults :-) He and Richard Heathfield are welcome to
return.

--
Some informative links:
news:news.annou nce.newusers
http://www.geocities.com/nnqweb/
http://www.catb.org/~esr/faqs/smart-questions.html
http://www.caliburn.nl/topposting.html
http://www.netmeister.org/news/learn2quote.html
Nov 14 '05 #71
CBFalconer wrote:
Does anyone know what happened to Dan?


Have you been wondering what you've been getting away with lately?

--
pete
Nov 14 '05 #72
CBFalconer <cb********@yah oo.com> wrote:
Does anyone know what happened to Dan?


Why couldn't somebody write him an email and ask how he is doing?

--
Stan Tobias
mailx `echo si***@FamOuS.Be dBuG.pAlS.INVALID | sed s/[[:upper:]]//g`
Nov 14 '05 #73
On 29 May 2005 23:51:41 GMT, "S.Tobias"
<si***@FamOuS.B edBuG.pAlS.INVA LID> wrote:
CBFalconer <cb********@yah oo.com> wrote:
Does anyone know what happened to Dan?


Why couldn't somebody write him an email and ask how he is doing?


Google says he's over at comp.std.c

Relax! His last post was on May the 16th (or perhaps he's busy posting
on c.l.c.moderated but we won't be able to see his posts for the next
two months ;-)

I'm much more interested in where my treacherous sidekick Stephan
Wilms is :-)
Nov 14 '05 #74
Chris Croughton <ch***@keristor .net> writes:
On 21 May 2005 16:40:23 GMT, Chris Torek
<no****@torek.n et> wrote:
In other words, if we have a system on which we can detect "failure
to align for any object whatsoever" by just using ordinary pointer
assignments, *then* that system will have to do 16-byte (or whatever)
alignment for a 3-byte malloc; but if the system handles "misaligned "
pointers without trouble, as long as they are not used to access
their misaligned objects, then -- because there will be no way for
the user to tell -- the as-if rule will allow us to implement
malloc(3) with just two-byte alignment.


Is there anything which says that alignments are always on a power of 2?
If not, then malloc() could have to be very wasteful. Imagine a system
(the DS9011, say) where a byte is 11 bits and the sizes (and alignments)
in bytes are:

Type Alignment
char 1
short 2
int 3
long 5
long long 7

and assigning

Thus malloc() would have to return an area aligned to at least 2*3*5*7
which is 210 bytes, even for malloc(1).


Here's a reason you might not have thought of why it's important
to always align for all possible element types.

Suppose we have a union type

union variant_union_t ag {

struct {
uint8_t kind;
} variant_indicat or_byte;

struct {
uint8_t kind;
char c[1024*1024];
} char_variant;

struct {
uint8_t kind;
short s[1024*1024];
} short_variant;

struct {
uint8_t kind;
int i[1024*1024];
} int_variant;

struct {
uint8_t kind;
long l[1024*1024];
} long_variant;

struct {
uint8_t kind;
long_long ll[1024*1024];
} long_long_varia nt;

};

...

union variant_union_t ag *v = malloc( sizeof v->variant_indica tor_byte );
if( ! v ) bail( "no memory" );
v->variant_indica tor_byte.kind = 0;

...

union variant_union_t ag new_v;
switch( some_value ){
case 0: break;
case 1: new_v = realloc( v, sizeof v->char_variant ); break;
case 2: new_v = realloc( v, sizeof v->short_varian t ); break;
case 3: new_v = realloc( v, sizeof v->int_variant ); break;
case 4: new_v = realloc( v, sizeof v->long_variant ); break;
case 5: new_v = realloc( v, sizeof v->long_long_vari ant ); break;

default: bail( "some_value has bogus value" );
}
if( ! new_v ) bail( "realloc failed" );
v = new_v;
v->variant_indica tor_byte.kind = some_value;

It's possible the realloc will succeed without moving the underlying
object. Thus, it must have been properly aligned at the very
beginning.

Of course, it's possible to imagine complicated strategies that note
sizes and possible alignments and force movement in cases where lack
of proper alignment may cause problems. At a systems level, though,
it's almost certainly better to have a simpler allocation algorithm
that just uses the least common multiple of all alignment
requirements. If you want something finer grained, use 'malloc()' to
get a big chunk and sub-allocate out of it. For 99+% of applications,
however, using malloc is good enough.

I have to admit that I got a good laugh when I saw that on a certain
proprietary OS (sold by a Redmond-based company) the storage overhead
for 'malloc()' is more than 50 bytes (on an x86 processor). I expect
though that most implementations are more reasonable.
Nov 14 '05 #75
Tim Rentsch wrote:
.... snip ...
I have to admit that I got a good laugh when I saw that on a
certain proprietary OS (sold by a Redmond-based company) the
storage overhead for 'malloc()' is more than 50 bytes (on an
x86 processor). I expect though that most implementations are
more reasonable.


It is quite conceivable. My nmalloc, for 32 bit operation under
DJGPP, uses 16 bytes, with an option for 24 (and more protection).
For a 64 bit system using 48 bytes is quite reasonable. My usage
is:

size
up pointer
down pointer (these two link to adjacent space)
free identifier and link (null when allocated)
free space link (these two manipulate the free space)
guard
allocated space
guard

The guards allow detection of overruns. Eliminating them and
putting the second free space link in the actual free space cuts it
down to 16 bytes. All this allows all operations to be O(1). If
you add some features (such as garbage collection, usage counts,
etc) you can easily push it up. Details of my version are at:

<http://cbfalconer.home .att.net/download/nmalloc.zip>

--
"I conclude that there are two ways of constructing a software
design: One way is to make it so simple that there are obviously
no deficiencies and the other way is to make it so complicated
that there are no obvious deficiencies." -- C. A. R. Hoare
Nov 14 '05 #76


Joe Wright wrote:
ra***********@g mail.com wrote:

[ much snippage ]

As I was going through the Recent replies on the realloc(),
I got some question and my annalysis on that, so regarding on these
please guide me where I fail on the theoritical and practical
Knowledge. I am not able to read all the thread in the replies as
due to some problem in the web server.

Point 1.

If we do the realloc then it means that we have allocated the
extended memory for the current memory, for which we have
reallocated it. Means I need not to free the previous memory
which I extendend to realloc if compiler allocates memory
(extended memory) from the place where intial memory was allocated.
Yes. You only free() the last address returned by realloc().
And we need to free if the memory is allocated by the
(realloc)in the new region.

No. There are no regions in play here.
so the key is to always free the memory when you reallocate
the memory by realloc fucntion.

No. You only free() the last address returned by realloc().


I got bit confused by your commnets so let me berif myself what
I said.

Suppose we have the memory of 10 bytes,
2000 to 2010;

Case 1:

now if i allocate the memory with the malloc like
malloc(6), Then let say that the memroy will be allocated
from 2000 to 2005,

Now I realloc it let say,
realloc(8), Then the memory will be allocated
from the 2000 to 2007,

Now for the above case we do not need to free the memory ...right.

Case 2:

Now take the other case,
we have to realloc with 20
realloc(20); Overe here The memory is not available

so the whole chunk of memory will be allocated in the new
available place. ... right.

let say it is allocated from 5000 to 5019,
now in this case we have to free the 2000 to 2005 memory loaction.

realloc returns the address of the location where the memory
has been alloctaed , in the above case will return 5000

what do you mean by the last address return ?? This is confusing
me. Please clarify.

How much I am correct on the Point 1 ?

Point 2.

what is the diffrence between the calloc() and malloc()
As far As I know the basic diffrence is that
1. malloc takes 1 argumnets while calloc takes two

Yes.
2. malloc initialise the memory with the garbage values while
calloc initialise it with 0 (Zero)

malloc() does not initialize memory.


correct i was wrong while using the words in my statement.
3. malloc allocates continious memeory i.e one Block while
calloc alloactes into the Block
calloc (100, 2) ,means two block of 100 memoty alloaction.

No. malloc() and calloc() both allocate contiguous memory. The two
arguments to calloc() have no particular signifigance. (100,2) allocates
200 bytes.


So what is the Diffrence then why specifically you need the
two arguments for this calloc() ? The block allocation
makes more sense for the two arguments passed to the
calloc (May Be I May Be Wrong Do Correct Me)

apart from the above is any more diffrence between them ??

Point 3.

This may be looks off topic to you but I have one thing to ask
is there any diffrence between the malloc and new ??

Yes. malloc() is defined by C, new is not.
Point 4.

why we need to derefrence the pointers once we are are done with our
work; I am not aware of garbage collection, And where I can find the
memory leak into the program ?

Wrong term. In C we dereference a pointer to yield the value to which it
points. free() does not do that. Rather free() de-allocates memory
allocated by its *alloc() siblings.
Thanks In Advance
Regards
Ranjeet

--
"If you want to post a followup via groups.google.c om, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson


--
Joe Wright mailto:jo****** **@comcast.net
"Everything should be made as simple as possible, but not simpler."
--- Albert Einstein ---


Nov 14 '05 #77


Joe Wright wrote:
ra***********@g mail.com wrote:

[ much snippage ]

As I was going through the Recent replies on the realloc(),
I got some question and my annalysis on that, so regarding on these
please guide me where I fail on the theoritical and practical
Knowledge. I am not able to read all the thread in the replies as
due to some problem in the web server.

Point 1.

If we do the realloc then it means that we have allocated the
extended memory for the current memory, for which we have
reallocated it. Means I need not to free the previous memory
which I extendend to realloc if compiler allocates memory
(extended memory) from the place where intial memory was allocated.
Yes. You only free() the last address returned by realloc().
And we need to free if the memory is allocated by the
(realloc)in the new region.

No. There are no regions in play here.
so the key is to always free the memory when you reallocate
the memory by realloc fucntion.

No. You only free() the last address returned by realloc().


I got bit confused by your commnets so let me berif myself what
I said.

Suppose we have the memory of 10 bytes,
2000 to 2010;

Case 1:

now if i allocate the memory with the malloc like
malloc(6), Then let say that the memroy will be allocated
from 2000 to 2005,

Now I realloc it let say,
realloc(8), Then the memory will be allocated
from the 2000 to 2007,

Now for the above case we do not need to free the memory ...right.

Case 2:

Now take the other case,
we have to realloc with 20
realloc(20); Overe here The memory is not available

so the whole chunk of memory will be allocated in the new
available place. ... right.

let say it is allocated from 5000 to 5019,
now in this case we have to free the 2000 to 2005 memory loaction.

realloc returns the address of the location where the memory
has been alloctaed , in the above case will return 5000

what do you mean by the last address return ?? This is confusing
me. Please clarify.

How much I am correct on the Point 1 ?

Point 2.

what is the diffrence between the calloc() and malloc()
As far As I know the basic diffrence is that
1. malloc takes 1 argumnets while calloc takes two

Yes.
2. malloc initialise the memory with the garbage values while
calloc initialise it with 0 (Zero)

malloc() does not initialize memory.


correct i was wrong while using the words in my statement.
3. malloc allocates continious memeory i.e one Block while
calloc alloactes into the Block
calloc (100, 2) ,means two block of 100 memoty alloaction.

No. malloc() and calloc() both allocate contiguous memory. The two
arguments to calloc() have no particular signifigance. (100,2) allocates
200 bytes.


So what is the Diffrence then why specifically you need the
two arguments for this calloc() ? The block allocation
makes more sense for the two arguments passed to the
calloc (May Be I May Be Wrong Do Correct Me)

apart from the above is any more diffrence between them ??

Point 3.

This may be looks off topic to you but I have one thing to ask
is there any diffrence between the malloc and new ??

Yes. malloc() is defined by C, new is not.
Point 4.

why we need to derefrence the pointers once we are are done with our
work; I am not aware of garbage collection, And where I can find the
memory leak into the program ?

Wrong term. In C we dereference a pointer to yield the value to which it
points. free() does not do that. Rather free() de-allocates memory
allocated by its *alloc() siblings.
Thanks In Advance
Regards
Ranjeet

--
"If you want to post a followup via groups.google.c om, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson


--
Joe Wright mailto:jo****** **@comcast.net
"Everything should be made as simple as possible, but not simpler."
--- Albert Einstein ---


Nov 14 '05 #78
It's easier to follow the discussion if you left-justify your text.
Indented text tends to look like it's a quotation.

ra***********@g mail.com writes:
[...]
I got bit confused by your commnets so let me berif myself what
I said.

Suppose we have the memory of 10 bytes,
2000 to 2010;
I think you mean 2000 to 2009.
Case 1:

now if i allocate the memory with the malloc like
malloc(6), Then let say that the memroy will be allocated
from 2000 to 2005,

Now I realloc it let say,
realloc(8), Then the memory will be allocated
from the 2000 to 2007,

Now for the above case we do not need to free the memory ...right.

Case 2:

Now take the other case,
we have to realloc with 20
realloc(20); Overe here The memory is not available

so the whole chunk of memory will be allocated in the new
available place. ... right.

let say it is allocated from 5000 to 5019,
now in this case we have to free the 2000 to 2005 memory loaction.


No. This is really simpler than you're making it out to be.

A successful call to malloc() or calloc() allocates a contiguous block
of memory and returns a pointer to it. (An unsuccessful call returns
NULL.) This memory eventually needs to be deallocated.

A successful call to realloc() allocates a contiguous block of memory,
copies the contents of the old block to the new block, deallocates the
old block, and returns a pointer to the new block. (An unsuccessful
calls returns NULL and leaves the old block alone.) This is true
regardless of whether the new size is less than, equal to, or greater
than the old size. Since the old block of memory has been
deallocated, the old pointer is indeterminate; you shouldn't try to do
anything with it.

Another way of looking at this is that realloc() effectively changes
the size (and possibly the location) of an allocated object. That
interpretation has some problems, though, because it's not really the
same object; it's a new object with the contents of the old object.

As it happens, an implementation will often (but not always) be able
to optimize the allocate/copy/deallocate sequence by re-using the old
object. The circumstances in which it can do this are
implementation-specific, and you shouldn't depend on any particular
behavior. Even if the new size is the same as the old size, the
implementation might use the realloc() as an opportunity to
consolidate free space.

Here's an example. Please note that the following is simplified code,
not to be used in real life. I'm ignoring the possibility that
malloc() or realloc() could fail.

char *ptr;
ptr = malloc(1000);
/*
* We have a 1000-byte buffer.
* After a while, we need more space.
*/
ptr = realloc(ptr, 2000);
/*
* Now we have a 2000-byte buffer.
* After a while, we don't need the whole thing.
*/
ptr = realloc(ptr, 500);
/*
* Now we have a 500-byte buffer.
* Eventaully, we're finished with it.
*/
free(ptr);

As this code executes ptr could point to three different locations in
memory, or it could point to the same location each time. We don't
know, and we don't care. Each call to realloc() deallocates the old
buffer and allocates a new one (possibly in the same place). We only
need to call free() when we're done with the last allocated buffer;
the others were all deallocated by realloc().

Why is this simplified code bad? First, I didn't check whether the
initial malloc() return NULL, indicating an allocation failure; if it
does, any attempt to use the allocated block can cause bad things
to happen. Second, if the realloc() call in
ptr = realloc(ptr, 2000);
fails, realloc() returns NULL, but the previously allocated block is
left alone. By assigning the result of realloc() to ptr, I may have
destroyed my only pointer to the allocated block, creating a memory
leak. If you want to be able to recover from a realloc() failure, you
need to assign the result to a separate pointer variable which you
then check for NULL.

[...]

Joe Wright wrote:
No. malloc() and calloc() both allocate contiguous memory. The two
arguments to calloc() have no particular signifigance. (100,2) allocates
200 bytes.


So what is the Diffrence then why specifically you need the
two arguments for this calloc() ? The block allocation
makes more sense for the two arguments passed to the
calloc (May Be I May Be Wrong Do Correct Me)


It's probably just for historical reasons. calloc() is typically used
to allocate space for an array; it's convenient to pass the element
size and the number of elements as separate arguments.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 14 '05 #79
ra***********@g mail.com wrote:

Joe Wright wrote:
ra*********** @gmail.com wrote:

[ much snippage ]
No. You only free() the last address returned by realloc().

I got bit confused by your commnets so let me berif myself what
I said.

Suppose we have the memory of 10 bytes,
2000 to 2010;


That would be eleven bytes.
Case 1:

now if i allocate the memory with the malloc like
malloc(6), Then let say that the memroy will be allocated
from 2000 to 2005,

Now I realloc it let say,
realloc(8), Then the memory will be allocated
from the 2000 to 2007,

Now for the above case we do not need to free the memory ...right.
Right.
Case 2:

Now take the other case,
we have to realloc with 20
realloc(20); Overe here The memory is not available

so the whole chunk of memory will be allocated in the new
available place. ... right.

let say it is allocated from 5000 to 5019,
now in this case we have to free the 2000 to 2005 memory loaction.
No. The realloc() function will do that for you.
realloc returns the address of the location where the memory
has been alloctaed , in the above case will return 5000

what do you mean by the last address return ?? This is confusing
me. Please clarify.


Use malloc() to allocate a region of memory of a certain size.

char *recon, *trial;
recon = malloc(20 * sizeof *recon);
if (!recon) bail(); /* Whatever you like when memory is exhausted */

Now you determine that the memory at recon needs to be increased.

trial = realloc(recon, 100 * sizeof *trial);

If realloc fails, trial is NULL and recon is still valid. If trial is
not NULL then realloc succeeded and trial is the new memory and recon
has been freed.

if (trial) recon = trial; /* if realloc succeeds */

Please read your C book and write more little programs.

--
Joe Wright mailto:jo****** **@comcast.net
"Everything should be made as simple as possible, but not simpler."
--- Albert Einstein ---
Nov 14 '05 #80

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

27
31465
by: Deephay | last post by:
Greetings all, I have a program that used the realloc() function to change the allocated size of a buffer, the program works with some arguments, but with some other arguments, it will show me the error message like: *** glibc detected *** realloc(): invalid next size: 0x0804c3a8 *** and then I inserted a perror("realloc") to see what happend, it says that:
0
9529
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10457
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10176
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10013
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7550
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6792
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5576
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3733
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2927
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.