473,785 Members | 2,423 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 4171
CBFalconer <cb********@yah oo.com> wrote:
"S.Tobias" wrote:
... snip ...

How about this: I say the Standard requires `malloc(1)' to return
at least enough space to accommodate `struct s'.
Stretched? Yes, but fits your assumptions better.

No. malloc has no way of knowing what such a requirement is.


Of course not. It would have to return maximum object size.
There would have to be maximum object size.

--
Stan Tobias
mailx `echo si***@FamOuS.Be dBuG.pAlS.INVALID | sed s/[[:upper:]]//g`
Nov 14 '05 #41
CBFalconer <cb********@yah oo.com> wrote:
As I read the following from N869:

7.20.3 Memory management functions

[#1] The order and contiguity of storage allocated by
successive calls to the calloc, malloc, and realloc
functions is unspecified. The pointer returned if the
allocation succeeds is suitably aligned so that it may be
assigned to a pointer to any type of object and then used to
access such an object or an array of such objects in the
space allocated (until the space is explicitly freed or
reallocated). Each such allocation shall yield a pointer to
an object disjoint from any other object. The pointer
returned points to the start (lowest byte address) of the
allocated space. If the space cannot be allocated, a null
pointer is returned. If the size of the space requested is
zero, the behavior is implementation-defined: either a null

^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^
pointer is returned, or the behavior is as if the size were
some nonzero value, except that the returned pointer shall
^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^ ^^^^^^^^^^
not be used to access an object. The value of a pointer
^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^ ^^^^^
that refers to freed space is indeterminate.

Is freeing NULL so generated accessing an object? Is freeing
non-NULL so generated accessing an object?


I should hope not. If it is, then

int *x;
x=malloc(100);
free(x);

invokes undefined behaviour. When the memory is received from malloc(),
it contains uninitialised bytes; it never is given a real value;
therefore, accessing it is accessing an uninitialised int value, which
invokes UB (may be a trap representation) . Therefore, if free() accessed
the object its argument points at, that code would possibly access a
trap representation. But TTBOMK, it's valid code. Because of this, I
conclude that so is

int *x;
x=malloc(0);
free(x);

since free() doesn't access *x in this case, either.

Richard
Nov 14 '05 #42
SM Ryan <wy*****@tang o-sierra-oscar-foxtrot-tango.fake.org> wrote:

[ Learn to quote, damn it. ]
ro******@ibd.nr c-cnrc.gc.ca (Walter Roberson) wrote:
# In article <11************ *@corp.supernew s.com>,
# SM Ryan <wy*****@tang o-sierra-oscar-foxtrot-tango.fake.org> wrote:
# >ro******@ibd.n rc-cnrc.gc.ca (Walter Roberson) wrote:
# ># If realloc() finds it necessary to move the memory block, then
# ># does it free() the previously allocated block?
#
# >You're over-specifying the function. What happens to the block is irrelevant
# >to understanding the function. Use the address returned by realloc; don't
# >worry about what it was before.
#
# The question is not over-specified if one is concerned about
# whether one is leaking memory. When your datasets are ~1 Gb each
# and you are handling them in a loop, you can't afford to allow memory
# to leak.

All you can do to prevent leaks is to match frees to allocs; you don't need to
know how the library is implemented to do that much. It's still leaking
you're stuck unless you can get the library source code.


Nope; that's probably why the OP wanted to know whether realloc() frees
the block it is passed. If it didn't, and could leak, one could still
implement a version which doesn't leak using malloc() and free(). From
the answers to the OP one can conclude that this isn't necessary; but
the question makes sense.

Richard
Nov 14 '05 #43
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).

Perhaps it is needed a version of malloc() which takes the size of the
base object as well as the number of them, so

type *p = nmalloc(sizeof( *p), num);

That could look up the size and work out the alignment (if it was not a
basic type then it could just use the sizeof value, since the alignment
for that type must be that value or a submultiple of it).

Chris C
Nov 14 '05 #44
# > # ># If realloc() finds it necessary to move the memory block, then
# > # ># does it free() the previously allocated block?

# Nope; that's probably why the OP wanted to know whether realloc() frees
# the block it is passed. If it didn't, and could leak, one could still
# implement a version which doesn't leak using malloc() and free(). From
# the answers to the OP one can conclude that this isn't necessary; but
# the question makes sense.

Some day you'll learn about modular programming. Most malloc libraries promise
not to leak if you match allocates and free properly. So with modular programming
you concentrate on the interface (matching allocates and frees) and not worry
about how the other modules fulfills its promises.

It suffices to know the interface and that you cannot trust the input pointer
to realloc, but rather the output pointer (whether they differ or no).

Trying to figure out if realloc calls free or immediately deallocates or unmaps
pages or anything else is breaking into the module without need. Even worrying
about whether memory moves is irrelevant. Suppose realloc is able to remap a
page so the phyical DRAM appears at a different address. Was memory moved or
not? MU.

--
SM Ryan http://www.rawbw.com/~wyrmwif/
The little stoner's got a point.
Nov 14 '05 #45
SM Ryan wrote:
# > # ># If realloc() finds it necessary to move the memory block, then # > # ># does it free() the previously allocated block?

# Nope; that's probably why the OP wanted to know whether realloc() frees # the block it is passed. If it didn't, and could leak, one could still # implement a version which doesn't leak using malloc() and free(). From # the answers to the OP one can conclude that this isn't necessary; but # the question makes sense.

Some day you'll learn about modular programming. Most malloc libraries promise not to leak if you match allocates and free properly. So with modular programming you concentrate on the interface (matching allocates and frees) and not worry about how the other modules fulfills its promises.
You have completely missed the point numerious times in this thread
with your remarks so let me spell it out for you: The OP was asking
about the "promises" of the "interface" provided by the Standard. It
was a completely valid question, you cannot properly use the function
in question without knowing the answer. Either realloc frees memory or
it doesn't. If it doesn't then you must free it yourself in specific
scenerios or introduce a memory leak. If is does, then attempting to
free the memory yourself would lead to undefined behavior. Try to
understand this before you post again.
It suffices to know the interface and that you cannot trust the input pointer to realloc, but rather the output pointer (whether they differ or no).
Trying to figure out if realloc calls free or immediately deallocates or unmaps pages or anything else is breaking into the module without need. Even worrying about whether memory moves is irrelevant. Suppose realloc is able to remap a page so the phyical DRAM appears at a different address. Was memory moved or not? MU.

--
SM Ryan http://www.rawbw.com/~wyrmwif/
The little stoner's got a point.


Rob Gamble

Nov 14 '05 #46
# > # > # ># If realloc() finds it necessary to move the memory block,
# then
# > # > # ># does it free() the previously allocated block?

# You have completely missed the point numerious times in this thread
# with your remarks so let me spell it out for you: The OP was asking
# about the "promises" of the "interface" provided by the Standard. It

Read the quoted question, clemclone.
does it free() the previously allocated block?
That's a question about the implementation of realloc not the interface.
In modular programming you don't worry about what realloc does. You only
worry about the interface. The interface has two important points on
realloc:

If you match allocates and frees, most mallocs promise not
to leak.

Use the output pointer of realloc and no longer the input.

Follow these a few other interface rules and and you don't have to
worry whether realloc calls free() or sbrk() or mapin() or anything
else.

# was a completely valid question, you cannot properly use the function
# in question without knowing the answer. Either realloc frees memory or
# it doesn't. If it doesn't then you must free it yourself in specific

You're not programming modularly if you need to know how realloc works.
For me it is sufficient to know that if I match frees with allocates
and use the current block pointers, the library promises to reuse memory
eventually. How and when are irrelevant to me.

# scenerios or introduce a memory leak. If is does, then attempting to
# free the memory yourself would lead to undefined behavior. Try to
# understand this before you post again.

Knowing the interface does not require knowing whether realloc calls
free(). I really don't care if realloc calls free. What I care about
is when I call free(), everything back to the original malloc or
realloc will be recycled.

--
SM Ryan http://www.rawbw.com/~wyrmwif/
Title does not dictate behaviour.
Nov 14 '05 #47
Richard Bos <rl*@hoekstra-uitgeverij.nl> wrote:
CBFalconer <cb********@yah oo.com> wrote:
Is freeing NULL so generated accessing an object? Is freeing
non-NULL so generated accessing an object?

I should hope not. If it is, then int *x;
x=malloc(100);
free(x); invokes undefined behaviour. When the memory is received from malloc(),
it contains uninitialised bytes; it never is given a real value;
therefore, accessing it is accessing an uninitialised int value, which
invokes UB


But free could write the object, which also counts as an access.

But anyway, I think that everybody now agrees that free() does not
access anything.

--
Stan Tobias
mailx `echo si***@FamOuS.Be dBuG.pAlS.INVALID | sed s/[[:upper:]]//g`
Nov 14 '05 #48
In article <pa************ *************** *@gmail.com>,
Robert Gamble <rg*******@gmai l.com> wrote:
The only thing being discussed here is alignmentment requirements. The
above quote states that your object created with malloc will be properly
*aligned* to hold any type, not that any type can actually be stored in it
if the space doesn't exist.


But no conforming program can tell the difference, so the statement
places no constraint on implementations .

-- Richard
Nov 14 '05 #49
Chris Croughton wrote:

Is there anything which says that alignments are always on a power of 2?
Not to my knowledge.
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).
ITYM "1*2*3*5*7. " Two marks off for bad penmanship.
Perhaps it is needed a version of malloc() which takes the size of the
base object as well as the number of them, so

type *p = nmalloc(sizeof( *p), num);

That could look up the size and work out the alignment (if it was not a
basic type then it could just use the sizeof value, since the alignment
for that type must be that value or a submultiple of it).


About a decade ago this question arose with respect to
calloc(), and the eventual conclusion was that calloc() had to
be "oblivious" to the significance of its two operands. That
is, calloc(2,8) and calloc(8,2) had to satisfy exactly the same
alignment constraints: the former could not legitimately decide
that only 2-byte alignment was required.

Mind you, much heated discussion preceded the conclusion,
and it is not certain that all the discussors agreed thereto.
"A man convinced against his will is of the same opinion still."

--
Eric Sosman
es*****@acm-dot-org.invalid
Nov 14 '05 #50

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

Similar topics

27
31457
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
9646
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9483
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
10346
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...
0
10157
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10096
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
8982
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6742
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();...
2
3658
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2887
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.