473,407 Members | 2,315 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,407 software developers and data experts.

Does realloc "move" a block it shortens?

I guess this program has undefined behavior, as far as ISO C
is concerned.

Anyone knows an implementation where realloc actually moves
a block that it shortens (as opposed to grows?)
#include <stdlib.h>
#include <string.h>
#include <stdio.h>

char *CopyStr(const char* s)
{
size_t n;
char *p;
n = strlen(s)+1;
if ((p = malloc(n))==NULL)
exit(EXIT_FAILURE);
memcpy(p,s,n);
return p;
}

void ShortenStr(char* p)
{
size_t n;
n = strlen(p);
p = realloc(p,n); /* could this move p ? */
p[n-1] = '\0';
}

int main(void)
{
char *p;
p = CopyStr("0123456789abcdef");
ShortenStr(p);
/* if realloc moved p, it is invalid */
puts(p);
return(EXIT_SUCCESS);
}
François Grieu
Nov 14 '05 #1
8 1671
Bonjour Francois, je n'ais pas compris juste que'est ce que tu veus
faire.Tu veus copier le string p, apres annuler les space vide, et le
metre en memoire?
Ci c'est ca, cherche sur google pour la method "*trim".

Been some time since i talked french. Just thought of doing so.

Hope this helps.
Later.

Nov 14 '05 #2
Francois Grieu wrote:

I guess this program has undefined behavior, as far as ISO C
is concerned.
Yes, for various reasons.

Anyone knows an implementation where realloc actually moves
a block that it shortens (as opposed to grows?)
So what, when correction is simple.

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

char *CopyStr(const char* s)
{
size_t n;
char *p;
n = strlen(s)+1;
if ((p = malloc(n))==NULL)
exit(EXIT_FAILURE);
memcpy(p,s,n);
return p;
}

void ShortenStr(char* p)
char *ShortenStr(char *p)
{
size_t n;
char *t;
n = strlen(p);
p = realloc(p,n); /* could this move p ? */
if (t = realloc(p, n+1)) t[n] = '\0';
return t;
p[n-1] = '\0';
}

int main(void)
{
char *p;
p = CopyStr("0123456789abcdef");
ShortenStr(p);
if (p = ShortenStr(p)) {
puts(p);
return EXIT_SUCCESS;
}
return EXIT_FAILURE;
/* if realloc moved p, it is invalid */
puts(p);
return(EXIT_SUCCESS);
}


However they are dangerous routines in that all strings handled
must reside in malloced memory.

--
"Churchill and Bush can both be considered wartime leaders, just
as Secretariat and Mr Ed were both horses." - James Rhodes.
"We have always known that heedless self-interest was bad
morals. We now know that it is bad economics" - FDR

Nov 14 '05 #3
Francois Grieu wrote:
I guess this program has undefined behavior, as far as ISO C
is concerned.

Anyone knows an implementation where realloc actually moves
a block that it shortens (as opposed to grows?)


I don't know whether any widely-available realloc()
implementations do this, but two of the implementations
I wrote as replacements for use in a particular program
would do so, under the right circumstances:

- One version *always* moved the data to a new location,
whether it grew, shrunk, or stayed the same size. It also
filled the old region with 0xDEADBEEF. The purpose was to
aid debugging by making it more likely that some kinds of
bugs would generate detectable errors.

- Another version used different memory "pools" for
allocations of different sizes: there was a pool for tiny
objects of <=16 bytes, another for objects whose size was
equal to that of a particular struct (the program used a
large number of instances of this struct), and a fairly
traditional implementation for all other sizes. The idea
was to avoid the usual malloc() overhead for small objects
and for the struct that was created in such huge numbers.
If you started with a 100-byte object, say, and shortened
it to 10 bytes, realloc() would try to move it from the
"everything else" pool to the "tiny" pool.

--
Er*********@sun.com

Nov 14 '05 #4

"Francois Grieu" <fg****@francenet.fr> wrote

Anyone knows an implementation where realloc actually moves
a block that it shortens (as opposed to grows?)

I've written lazy implementations which just call malloc() followed by
memcpy().
Nov 14 '05 #5
Francois Grieu <fg****@francenet.fr> wrote in message news:<fg**************************@individual.net> ...
I guess this program has undefined behavior, as far as ISO C
is concerned.

Anyone knows an implementation where realloc actually moves
a block that it shortens (as opposed to grows?)

AFAIK, there's no restriction on realloc() moving a block that's
shortened (I don't have a copy of the Standard handy, though, so don't
treat that as gospel).
There is a bug in the code below, though, and that may be what's
giving you problems.

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

char *CopyStr(const char* s)
{
size_t n;
char *p;
n = strlen(s)+1;
if ((p = malloc(n))==NULL)
exit(EXIT_FAILURE);
memcpy(p,s,n);
return p;
}

void ShortenStr(char* p)
Since *p can potentially be written to if realloc() relocates the
memory, it should be passed by reference, i.e.

void ShortenStr(char **p)
{
size_t n;
n = strlen(p);
n = strlen(*p);
p = realloc(p,n); /* could this move p ? */
*p = realloc (*p,n);
p[n-1] = '\0';
(*p)[n-1] = '\0';
}

int main(void)
{
char *p;
p = CopyStr("0123456789abcdef");
ShortenStr(p);
ShortenStr(&p);
/* if realloc moved p, it is invalid */
puts(p);
return(EXIT_SUCCESS);
}
François Grieu

Nov 14 '05 #6
In article <fg**************************@individual.net>,
Francois Grieu <fg****@francenet.fr> wrote:
I guess this program has undefined behavior, as far as ISO C
is concerned.

Anyone knows an implementation where realloc actually moves
a block that it shortens (as opposed to grows?)


It is quite possible. There are malloc implementations that try to
suballocate all blocks of size x, 2^k <= x < 2^(k+1), from the same
block. On such an implementation, if you call realloc (malloc (3000),
1500), the block will be reallocated in such an implementation.
Nov 14 '05 #7
I asked
Anyone knows an implementation where realloc actually moves
a block that it shortens (as opposed to grows?)


"Malcolm" <ma*****@55bank.freeserve.co.uk> wrote:
} I've written lazy implementations which just call malloc() followed by
} memcpy().
Christian Bau <ch***********@cbau.freeserve.co.uk> wrote:
] There are malloc implementations that try to suballocate all blocks
] of size x, 2^k <= x < 2^(k+1), from the same block.

Thanks, I'm convinced: it can happen.
Thanks for those that jumped to fix my crafted-for-the-purpose-sample code.
My actual problem is that a script compiler I maintain
- mallocs a block for to some maximum size, before knowing the final size
(typically much smaller)
- while parsing and filling the block, keeps the adresse of some
locations in the block that will need later fixing
- resizes the bloc to its final size, with a runtime test that
realloc did not move the block (it never happened so far)
- much later, fixes the references.

François Grieu
Nov 14 '05 #8
On Sat, 11 Sep 2004 08:58:44 +0200, Francois Grieu
<fg****@francenet.fr> wrote:

snip
Thanks for those that jumped to fix my crafted-for-the-purpose-sample code.
My actual problem is that a script compiler I maintain
- mallocs a block for to some maximum size, before knowing the final size
(typically much smaller)
- while parsing and filling the block, keeps the adresse of some
locations in the block that will need later fixing
- resizes the bloc to its final size, with a runtime test that
realloc did not move the block (it never happened so far)
- much later, fixes the references.

It might be worthwhile to review the code that fixes the references to
determine if there is any undefined behavior when the block is
relocated. It might be easier to maintain offsets or displacements
which will be invariant regardless or relocation.
<<Remove the del for email>>
Nov 14 '05 #9

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

Similar topics

20
by: Jonas | last post by:
Hi, I'm 99 % sure that Standard C guarantees to do a memory move inside realloc() in case the new, returned memory block (address) is different than the original one. Can any C expert confirm...
1
by: David Resnick | last post by:
I had a problem going from gcc 2.96 to gcc 3.2.3 and narrowed it down to the following code. The question is whether the problem is undefined behavior on the code's part or a compiler bug. ...
31
by: bilbothebagginsbab5 AT freenet DOT de | last post by:
Hello, hello. So. I've read what I could find on google(groups) for this, also the faq of comp.lang.c. But still I do not understand why there is not standard method to "(...) query the...
7
by: Tim Conner | last post by:
Hi, I am an ex-delphi programmer, and I having a real hard time with the following simple code (example ): Which is the equivalent to the following code ? var chars : PChar; sBack, s :...
1
by: melinda | last post by:
How do you set up a MDI interface so that one of the MDI forms can be dragged outside of the parent form. For example, in Visual Studio, you can do this with some of the windows. Is this MDI? ...
1
by: David Veeneman | last post by:
In VS.NET 1.1, when I commented-out a block of code, VS.NET put the comment slashes on the left margin, rather than next to the code. This made it very easy to identify blocks of code that I had...
7
by: Michael R | last post by:
It's an interesting question, as I see it. I have a form, in which there are a few command buttons, which change color when the mouse is on top of them (On Mouse Move). Now, I want the color to be...
3
by: Gina_Marano | last post by:
Hey all, It appears that if I File.Move a large file 1GB from one network location to another location it is really slow. example. from: \\myserver\myfolder\a\largefile.txt to:...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
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,...
0
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...
0
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,...
0
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...
0
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...
0
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,...

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.