473,657 Members | 2,378 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Simple realloc() question

I'm sorry to always bother you guys on simple C topics... but here
again I go :)

What does the standard C99 (and if you have knowledge, pre-C99 also)
say about the behavior of realloc() on different new sizes?

AFAIR, realloc with a bigger size must return the new address, or NULL
if it fails. I was wondering, what happens when you ask realloc to
shrink the allocated space? Will it free the remaining memory or not?

Thanks to anyone!
--
Sensei <senseiwa@Apple 's mail>

Research (n.): a discovery already published by a chinese guy one month
before you, copying a russian who did it in the 60s.

Feb 7 '07 #1
11 1619
Sensei wrote:
I'm sorry to always bother you guys on simple C topics... but here
again I go :)

What does the standard C99 (and if you have knowledge, pre-C99 also)
say about the behavior of realloc() on different new sizes?

AFAIR, realloc with a bigger size must return the new address, or NULL
if it fails.
Correct.
I was wondering, what happens when you ask realloc to
shrink the allocated space? Will it free the remaining memory or not?
As far as the standard is concerned, realloc is allowed to return a
null pointer even when asking for less memory than you already have.
It is also allowed to return a non-null pointer that points to more
memory than the amount you asked for.

Feb 7 '07 #2
Sensei wrote, On 07/02/07 08:51:
I'm sorry to always bother you guys on simple C topics... but here again
I go :)

What does the standard C99 (and if you have knowledge, pre-C99 also) say
about the behavior of realloc() on different new sizes?

AFAIR, realloc with a bigger size must return the new address, or NULL
if it fails.
Note that the new address *might* be the same as the old address.
I was wondering, what happens when you ask realloc to
shrink the allocated space? Will it free the remaining memory or not?
It might move on shrinking as well. Whatever happens if the realloc
succeeds (it could fail on shrinking) you can no longer access the
memory you have said you no longer want.
--
Flash Gordon
Feb 7 '07 #3
Sensei wrote:
I'm sorry to always bother you guys on simple C topics... but here
again I go :)

What does the standard C99 (and if you have knowledge, pre-C99 also)
say about the behavior of realloc() on different new sizes?
Nothing that specific.
AFAIR, realloc with a bigger size must return the new address, or NULL
if it fails.
If by "new" you mean "different from the old", then this is not the case.
'realloc' with a bigger size might quite possibly return the same address.
I was wondering, what happens when you ask realloc to
shrink the allocated space? Will it free the remaining memory or not?
If by "free" you me "make available to further allocation requests", then the
answer is "it normally should". But there are many things there that can be done
differently.

--
Best regards,
Andrey Tarasevich
Feb 7 '07 #4
On Feb 7, 10:02 am, Flash Gordon <s...@flash-gordon.me.ukwro te:
Sensei wrote, On 07/02/07 08:51:
I'm sorry to always bother you guys on simple C topics... but here again
I go :)
What does the standard C99 (and if you have knowledge, pre-C99 also) say
about the behavior of realloc() on different new sizes?
AFAIR, realloc with a bigger size must return the new address, or NULL
if it fails.

Note that the new address *might* be the same as the old address.
Not really. The old pointer value is indeterminate if realloc returns
a non-null pointer, so comparing old and new pointer would invoke
undefined behavior.

Feb 7 '07 #5
In article <11************ **********@a34g 2000cwb.googleg roups.com>,
christian.bau <ch***********@ cbau.wanadoo.co .ukwrote:
AFAIR, realloc with a bigger size must return the new address, or NULL
if it fails.
>Note that the new address *might* be the same as the old address.
>Not really. The old pointer value is indeterminate if realloc returns
a non-null pointer, so comparing old and new pointer would invoke
undefined behavior.
If you really want to, you can test whether the address has changed by
copying the old pointer to a suitably-sized byte array before calling
realloc(), and doing the same with the new one. I suppose this could
give false positives if the pointer has padding bits and realloc()
sets them differently.

-- Richard
--
"Considerat ion shall be given to the need for as many as 32 characters
in some alphabets" - X3.4, 1963.
Feb 7 '07 #6
On Feb 8, 12:09 am, "christian. bau" <christian....@ cbau.wanadoo.co .uk>
wrote:
On Feb 7, 10:02 am, Flash Gordon <s...@flash-gordon.me.ukwro te:
Sensei wrote, On 07/02/07 08:51:
I'm sorry to always bother you guys on simple C topics... but here again
I go :)
What does the standard C99 (and if you have knowledge, pre-C99 also) say
about the behavior of realloc() on different new sizes?
AFAIR, realloc with a bigger size must return the new address, or NULL
if it fails.
Note that the new address *might* be the same as the old address.

Not really. The old pointer value is indeterminate if realloc returns
a non-null pointer, so comparing old and new pointer would invoke
undefined behavior.
Yes really. He didn't mention any comparisons, he just stated that the
pointer can have the same value. N1124 says (7.20.3.4): "The realloc
function returns a pointer to the new object (which may have the same
value as a pointer to the old object), or a null pointer if the new
object could not be allocated."
--
WYCIWYG

Feb 8 '07 #7
Richard Tobin wrote:
christian.bau <ch***********@ cbau.wanadoo.co .ukwrote:
.... snip stuff that had no corresponding attribution lines ...
>
>Not really. The old pointer value is indeterminate if realloc
returns a non-null pointer, so comparing old and new pointer
would invoke undefined behavior.

If you really want to, you can test whether the address has
changed by copying the old pointer to a suitably-sized byte array
before calling realloc(), and doing the same with the new one. I
suppose this could give false positives if the pointer has
padding bits and realloc() sets them differently.
<academic interest only>
You can beat that by using the %p specifier in a sprintf call.

char inputvalue[ENOUGH];
char outputvalue[ENOUGH];

void *p, *tmp;

p = malloc(SOMETHIN G];
sprintf(inputva lue, "%p", p);
if (tmp = realloc(p, SOMETHINGELSE)) p = tmp;
else {
puts("No memory"); exit(EXIT_FAILU RE);
}
sprintf(outputv alue, "%p, p);
if (strcmp(inputva lue, outputvalue)) puts("pointer changed");
else puts("pointer unchanged after size change");

with suitable #includes and #defines, should be portable.
</academic interest only>

--
<http://www.cs.auckland .ac.nz/~pgut001/pubs/vista_cost.txt>
<http://www.securityfoc us.com/columnists/423>

"A man who is right every time is not likely to do very much."
-- Francis Crick, co-discover of DNA
"There is nothing more amazing than stupidity in action."
-- Thomas Matthews
Feb 8 '07 #8
CBFalconer wrote, On 08/02/07 00:13:
Richard Tobin wrote:
>christian.ba u <ch***********@ cbau.wanadoo.co .ukwrote:
... snip stuff that had no corresponding attribution lines ...
>>Not really. The old pointer value is indeterminate if realloc
returns a non-null pointer, so comparing old and new pointer
would invoke undefined behavior.
If you really want to, you can test whether the address has
changed by copying the old pointer to a suitably-sized byte array
before calling realloc(), and doing the same with the new one. I
suppose this could give false positives if the pointer has
padding bits and realloc() sets them differently.

<academic interest only>
You can beat that by using the %p specifier in a sprintf call.

char inputvalue[ENOUGH];
char outputvalue[ENOUGH];

void *p, *tmp;

p = malloc(SOMETHIN G];
sprintf(inputva lue, "%p", p);
if (tmp = realloc(p, SOMETHINGELSE)) p = tmp;
else {
puts("No memory"); exit(EXIT_FAILU RE);
}
sprintf(outputv alue, "%p, p);
if (strcmp(inputva lue, outputvalue)) puts("pointer changed");
else puts("pointer unchanged after size change");

with suitable #includes and #defines, should be portable.
</academic interest only>
There is a guarantee that having printed it with %p you c
an get it back with scanf, however I am not aware of any guarantee that
each time you print the same pointer value you will get the same
representation. After all, if it just prints the bytes in hex then if
there are multiple ways of producing the same pointer value the printed
versions would be different.
--
Flash Gordon
Feb 8 '07 #9
"christian. bau" wrote:
>
On Feb 7, 10:02 am, Flash Gordon <s...@flash-gordon.me.ukwro te:
Sensei wrote, On 07/02/07 08:51:
I'm sorry to always bother you guys on simple C topics... but here again
I go :)
What does the standard C99 (and if you have knowledge, pre-C99 also) say
about the behavior of realloc() on different new sizes?
AFAIR, realloc with a bigger size must return the new address, or NULL
if it fails.
Note that the new address *might* be the same as the old address.

Not really. The old pointer value is indeterminate if realloc returns
a non-null pointer, so comparing old and new pointer would invoke
undefined behavior.
Just because you technically can't compare the old and new pointers
doesn't mean that they aren't the same. Besides, he said nothing
about comparing the old and new. He merely mentioned that the new
address might be the same as the old one.
What about this untested code?

==========

#include <stdlib.h>

/* Assumption:
* The output of "%p" formatting must fit in 127 bytes.
*/
int realloc_test(ch ar *oldpt, size_t newsize, char **newpt)
{
char oldbuf[128], newbuf[128];

sprintf(oldbuf, "%p",(void *)oldpt);

*newpt = realloc(oldpt,n ewsize);
sprintf(newbuf, "%p",(void *)*newpt);

#if DEBUG
printf("%s\n%s\ n",oldbuf,newbu f);
#endif
if ( strcmp(oldbuf,n ewbut) == 0 )
{
return 1;
}
else
{
return 0;
}
}

==========

--
+-------------------------+--------------------+-----------------------+
| Kenneth J. Brody | www.hvcomputer.com | #include |
| kenbrody/at\spamcop.net | www.fptech.com | <std_disclaimer .h|
+-------------------------+--------------------+-----------------------+
Don't e-mail me at: <mailto:Th***** ********@gmail. com>
Feb 8 '07 #10

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

Similar topics

20
3053
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 this to me, please? Thanks, Jonas PS. I using C90, not C99--if it makes a difference.
9
2349
by: mordac | last post by:
Hi, writing a heap ADT, need to handle insertion into the heap when it is full. Attempting to use realloc to do this, but realloc is changing the contents of my heap! The following is my incHeapSize function, which is supposed to increase the malloced space for an integer array by 1: Heap incHeapSize(Heap aHeap) { int* tempHeap; aHeap->maxSize++; tempHeap = realloc(aHeap->heapArray, aHeap->maxSize);
8
5104
by: Ross A. Finlayson | last post by:
I'm trying to write some C code, but I want to use C++'s std::vector. Indeed, if the code is compiled as C++, I want the container to actually be std::vector, in this case of a collection of value types or std::vector<int>. So where I would use an int* and reallocate it from time to time in C, and randomly access it via , then I figure to copy the capacity and reserve methods, because I just need a growable array. I get to considering...
86
4117
by: Walter Roberson | last post by:
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...
5
1811
by: James S. Singleton | last post by:
Thanks to everybody who provided an answer to my previous question on this. I am trying to grasp the nitty-gritty details of this, and I am having difficulties understanding some of the issues involved. According to the man page (and I quote) realloc(void *ptr, size_t size) changes the size of the memory block pointed to by ptr to size bytes. The contents will be unchanged to the minimum of the old and new sizes; newly allocated memory...
23
410
by: James Brown | last post by:
Hi all, I just wanted to make sure I understand realloc void *realloc( void *memblock, size_t size ); 1. when memblock is zero, realloc behaves like malloc 2. when memblock is non-zero, and size is the same as the last time (i.e. memblock already big enough), then realloc is a "no-op" I think #1 is true, but I am not sure about #2
27
31360
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:
31
12753
by: banansol | last post by:
Hi, I just want to get this right. A call to realloc() will return NULL on error and the original memory is left untouched, both when requesting a larger or a smaller size that the original, right? But a call to realloc() with size set to zero is equivalent to free(), with returns void. Does that mean that a call to realloc() can fail when shinking memory except when
4
3500
by: Kenneth Brody | last post by:
I looked at my copy of n1124, and I didn't see anything about this particular situation... What happens if you realloc() to a size of zero? Implementations are allowed to return NULL on malloc(0), and realloc() says it reutrns NULL on failure. (And, on failure, the old pointer has not been freed.) Is it possible for an implementation to return NULL for realloc(ptr,0)
0
8312
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
8732
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...
0
8606
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...
0
7337
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...
1
6169
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
4159
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4318
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
1959
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1622
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.