473,836 Members | 2,136 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

realloc(): invalid next size

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:

realloc: Illegal seek
the realloc() is in a loop:

for (m = 0; m < len; m++) {
if (isspace(data[m]) || ispunct(data[m]) ||
isdigit(data[m]))
printf("%c", data[m]);
else {
p = min(strcspn(&da ta[m], " "),
strcspn(&data[m], "\t"),
strcspn(&data[m], "\r"),
strcspn(&data[m], "\n"));
key = realloc(key, p);
strncpy(key, &data[m], p);
key[p] = '\0';
trans(key, p);
m = m + p - 1;
}
}

and the "key" is already malloced before the loop:

char *key = malloc(1);

Any suggestion could be helpful, thx very much!

Deephay
Apr 11 '06
27 31494

"Pedro Graca" <he****@dodgeit .com> wrote in message
news:sl******** ***********@ID-203069.user.ind ividual.net...
Rod Pemberton wrote:
"Pedro Graca" <he****@dodgeit .com> wrote in message
news:sl******** ***********@ID-203069.user.ind ividual.net...
Right. Let's run "my_realloc(val id_old_pointer, 0);" step by step ...

void *my_realloc (void *s1, size_t size)
{
void *s2=NULL;
/* s1 --> valid_old_point er
* s2 --> NULL
* size --> 0 */

if (size!=0||s1==N ULL)
s2 = malloc(size);
else
free(s1);
/* s1 --> free'd valid_old_point er
* s2 --> NULL
* size --> 0 */


Correct to here.
if (s1!=NULL)
memcpy(s2, s1, size);
/* And here we go ...


No we don't. s1!=NULL is true. This if() is skipped. s1 is freed, but is
_NOT_ NULL. It retains it's prior value. Why? Because, the argument to
free() is passed by value. That means s1 isn't changed.

free() is declared as:
void free(void *ptr);

For free() to return a NULL as you seem to think, it'd need to be declared
as (this would also change the way it is called):
void free(void **ptr);

HTH,
Rod Pemberton
Apr 13 '06 #21

"Rod Pemberton" <do*********@so rry.bitbuck.cmm > wrote in message
news:e1******** **@localhost.lo caldomain...

"Pedro Graca" <he****@dodgeit .com> wrote in message
news:sl******** ***********@ID-203069.user.ind ividual.net...
Rod Pemberton wrote:
"Pedro Graca" <he****@dodgeit .com> wrote in message
news:sl******** ***********@ID-203069.user.ind ividual.net...


Right. Let's run "my_realloc(val id_old_pointer, 0);" step by step ...

void *my_realloc (void *s1, size_t size)
{
void *s2=NULL;
/* s1 --> valid_old_point er
* s2 --> NULL
* size --> 0 */

if (size!=0||s1==N ULL)
s2 = malloc(size);
else
free(s1);
/* s1 --> free'd valid_old_point er
* s2 --> NULL
* size --> 0 */


Correct to here.
if (s1!=NULL)
memcpy(s2, s1, size);
/* And here we go ...


Sorry, you're right. _I_ must have been thinking free NULLed ...

RP
Apr 13 '06 #22

"Rod Pemberton" <do*********@so rry.bitbuck.cmm > wrote in message
news:e1******** **@localhost.lo caldomain...

"Rod Pemberton" <do*********@so rry.bitbuck.cmm > wrote in message
news:e1******** **@localhost.lo caldomain...

"Pedro Graca" <he****@dodgeit .com> wrote in message
news:sl******** ***********@ID-203069.user.ind ividual.net...
Rod Pemberton wrote:
> "Pedro Graca" <he****@dodgeit .com> wrote in message
> news:sl******** ***********@ID-203069.user.ind ividual.net...

Sorry, you're right. _I_ must have been thinking free NULLed ...


Pedro, is this one any better?

void *my_realloc (void *s1, size_t size)
{
void *s2=NULL;

if(size!=0)
s2 = malloc(size);
if(s1!=NULL&&si ze!=0)
memcpy(s2, s1, size);
if(s1!=NULL)
free(s1);
return(s2);
}
Rod Pemberton
Apr 13 '06 #23
Rod Pemberton wrote:
Rod Pemberton
Pedro Graca

[snip a lot of confusion]

Now that /that/ is taken care of ... -- but I may still come back to it
in a day or two :)
Does this program

#include <stdlib.h>
#include <string.h>
int main(void) {
void * ptr = malloc(42);
if (ptr) {
free(ptr);

memcpy(NULL, ptr, 0);
memcpy(ptr, NULL, 0);
}
return 0;
}

invoke UB at any point?

Or, because the number of bytes "to copy" is 0 (zero) it doesn't matter
what the pointers point to?

--
If you're posting through Google read <http://cfaj.freeshell. org/google>
Apr 13 '06 #24
Pedro Graca said:
Does this program

#include <stdlib.h>
#include <string.h>
int main(void) {
void * ptr = malloc(42);
if (ptr) {
free(ptr);

memcpy(NULL, ptr, 0);
memcpy(ptr, NULL, 0);
}
return 0;
}

invoke UB at any point?
Four points.
Or, because the number of bytes "to copy" is 0 (zero) it doesn't matter
what the pointers point to?


It matters. The definition of memcpy requires that the two pointer
parameters each point to an object. NULL does not point to an object (and,
indeed, is *guaranteed* not to point to an object). Furthermore, the value
of ptr is indeterminate, and yet you are evaluating it. This evaluation
takes place *before* memcpy is even called.

Therefore, and for two different reasons, the behaviour is undefined,
irrespective of the number of bytes to be copied.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Apr 13 '06 #25
>"Chris Torek" <no****@torek.n et> wrote in message
news:e1******* *@news2.newsguy .com...
With a few exceptions (noted below), realloc() is essentially an
optimized version of the following:

void *realloc(void *old, size_t newsize) {
size_t oldsize = __some_sort_of_ magic_done_here (old);
void *new;

new = malloc(newsize) ;
if (new != NULL) {
memcpy(new, old, oldsize < newsize ? oldsize : newsize);
free(old);
}
return new;
}
In article <e1**********@l ocalhost.locald omain>,
Rod Pemberton <do*********@so rry.bitbuck.cmm > wrote:
Hmm, no NULL check for old?
I was (admittedly sloppily/non-Standard-ly) omitting it on the
assumption that memcpy(new, NULL, 0) would be a no-op rather than
causing problems. Better to check. Of course, a "real" realloc()
(a) has to supply the "magic" that figures out the old size, and
(b) should (but does not have to) optimize those cases where the
realloc can be done without copying. The intent was really just
to show "minimal required behavior", as it were.
(Seriously: C89 specifically said that realloc(NULL,n) was equivalent
to malloc(n), and malloc(0) *could* be equivalent to malloc(1); it
then also said that realloc(p,0) was equivalent to free(p); so what
then is realloc(NULL,0) -- is it like malloc(0) and hence like
malloc(1), or is it just free(NULL)?)

If your question wasn't rhetorical, this realloc probably answers your
question. [code snipped]


Alas, no code can answer the question unless that code comes in
the form of a response to a Defect Report to the C standards people.

The problem is that the text of the Standard is written in a
semi-formal English, leaving some items ambiguous. Sometimes the
ambiguity is intentional, to allow different implementations to do
different things. Sometimes it is, I think at least, just pointless
ambiguity. (The *answer* to my question is not usually very
interesting, though. I tend not to realloc() to size 0 and therefore
not care what it might or might not do.)

(I understand why the Standards folks did not want to use something
more formal -- whether mathematical notation or actual code -- to
define things. I think it was at least occasionally the wrong
decision, though. It would be possible to specify things precisely,
then use English text to relax the requirements, instead of using
English to specify things laxly. That might reduce the flexibility
to implementors, but it could greatly improve the predictability to
users.)
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.
Apr 13 '06 #26
Rod Pemberton wrote:
Pedro, is this one any better?

[snip my_realloc() implementation]

Yes :)
But I'm not the best guy around here to be asked stuff.

--
If you're posting through Google read <http://cfaj.freeshell. org/google>
Apr 13 '06 #27

"Chris Torek" <no****@torek.n et> wrote in message
news:e1******** *@news1.newsguy .com...
"Chris Torek" <no****@torek.n et> wrote in message
news:e1******* *@news2.newsguy .com...
With a few exceptions (noted below), realloc() is essentially an
optimized version of the following:

In article <e1**********@l ocalhost.locald omain>,
Rod Pemberton <do*********@so rry.bitbuck.cmm > wrote:
Hmm, no NULL check for old?


I was (admittedly sloppily/non-Standard-ly) omitting it on the
assumption that memcpy(new, NULL, 0) would be a no-op rather than
causing problems. Better to check. Of course, a "real" realloc()
(a) has to supply the "magic" that figures out the old size, and
(b) should (but does not have to) optimize those cases where the
realloc can be done without copying. The intent was really just
to show "minimal required behavior", as it were.


That's why I mentioned: "If your question wasn't rhetorical."
Unfortunately, Pedro had to beat me up pretty good to get me to realize I
wasn't reading my code as written, but thinking my code as I thought it
worked when I wrote it... :-(
The problem is that the text of the Standard is written in a
semi-formal English, leaving some items ambiguous. Sometimes the
ambiguity is intentional, to allow different implementations to do
different things. Sometimes it is, I think at least, just pointless
ambiguity. (The *answer* to my question is not usually very
interesting, though. I tend not to realloc() to size 0 and therefore
not care what it might or might not do.)

The problem is that they stripped the historical context and the "C is built
upon assembly language" context that helped define earlier C
implementations . There are things in the C89/90 spec. that I'm sure were
upper boundaries for 16-bit compilers. Unfortunately, people who didn't use
C in the '80s or early 90's usually think they are the lower boundaries.
The spec. of course is sufficiently vauge that they can be upper boundaries
for a 16-bit compiler and lower boundaries for a 32-bit one.
(I understand why the Standards folks did not want to use something
more formal -- whether mathematical notation or actual code -- to
define things. I think it was at least occasionally the wrong
decision, though. It would be possible to specify things precisely,
then use English text to relax the requirements, instead of using
English to specify things laxly. That might reduce the flexibility
to implementors, but it could greatly improve the predictability to
users.)


Even here most people say: "It invokes undefined behavior." "Invokes" to me
implies a guaranteed result. It's closer to "will cause" than "may cause."
Unfortunately or fortunately, almost all cases of UB work as intended and
don't cause any blatantly obvious defect like a crash, lockup, or memory
corruption.
Rod Pemberton
Apr 14 '06 #28

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

Similar topics

36
2839
by: Roy | last post by:
Hi all : My code below : #include <stdio.h> #include <string.h> #include <stdlib.h> char *cat(char *s, const char *t) { char *tmp;
9
307
by: James S. Singleton | last post by:
If we do q = realloc(p, 128) ; and on (successful) return of realloc, q != p, must the block pointed to by p be explicitly freed, or has realloc freed it already?
10
1525
by: James S. Singleton | last post by:
Thanks everybody for your replies. I gather that: a) How to obtain the size of the memory region pointed to by ptr in realloc(ptr, size) is implementation-dependent. b) Implementing realloc(ptr, size) using malloc(), memcpy() and free() alone, without knowing the size of the memory region pointed to by ptr, is just not possible.
4
4024
by: alex323 | last post by:
Hey. I must have an array that can be resized dynamically. I have coded an implementation of it using malloc/realloc, but I am getting a runtime error as seen below in GDB: *** glibc detected *** realloc(): invalid next size: 0x08054828 *** Program received signal SIGABRT, Aborted. 0xffffe410 in __kernel_vsyscall () (gdb) bt
28
3885
by: bwaichu | last post by:
Is it generally better to set-up a buffer (fixed sized array) and read and write to that buffer even if it is larger than what is being written to it? Or is it better to allocate memory and realloc it for the size of the what is being written each time? In other words, what is the decision factor between deciding to use a fixed size buffer or allocating memory space and reallocing the size? I don't think the code below is optimal...
2
525
by: solanki.chandrakant | last post by:
hi i have fedora linux 4 and i have simple realloc program which i am included here... plz help me to overcome the realloc to pointer to character variable. The program working 2 times but more than 2 times it gives error : realloc() - invalid next size. #include <stdio.h> #include <stdlib.h>
64
8394
by: Robert Seacord | last post by:
The C standard doesn't say anything about what happens when you call realloc with a size argument of 0. Both glibc and openbsd appear to return a valid pointer to a zero-sized object.. e.g. the return of a malloc(0). Does anyone know of a runtime where realloc() free'ed the object and then returned NULL? If so, it would make the following idiom for realloc() exploitable. Here's the idiom, snagged from an openbsd man page: if ((p2 =...
29
7889
by: marvinla | last post by:
Hello! I'm a beginner in C, and I'm having trouble with a pointer-to-pointer reallocation. This piece of code works well, but Valkyrie warns some parts (pointed below), and is breaking my real code. #include <stdio.h> #include <stdlib.h>
7
1855
by: lancer6238 | last post by:
Hi, I'm writing a program that separates a set of integers into groups and then quicksort each group individually. However, I'm having problems with my realloc() function. (Pardon me if the indentation is weird. There's no preview button here and I can't tell if my indentation is correct.) #include <stdio.h> #include <stdlib.h>
0
9810
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
10821
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
10527
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
10241
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
9358
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
6973
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
5642
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...
1
4441
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
4001
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.