473,889 Members | 1,692 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 #1
27 31516
Deephay <tu*****@gmail. com> wrote:
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"));
Why not simply use strcspn(&data[m], " \t\r\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);


Hard to say what the real problem is without any object or function
definitions, but two questions spring to mind:
- does this occur immediately, or after a few iterations;
- what actually is the value of p (and if this code isn't complete, of
key) at the point where it produces the error?

Richard
Apr 11 '06 #2
Richard Bos wrote:
Deephay <tu*****@gmail. com> wrote:
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"));
Why not simply use strcspn(&data[m], " \t\r\n")?

I have to get the index where the first "space" locates.
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);
Hard to say what the real problem is without any object or function
definitions, but two questions spring to mind:
- does this occur immediately, or after a few iterations;
- what actually is the value of p (and if this code isn't complete, of
key) at the point where it produces the error?

the error occurred after a few iterations, the first realloc will always
success.
the p is always larger than 0, I have tested. Actually it will be a
quite normal
value where the error produced, say, 7, 8, or whatever...

What I think now is that it might be a bug of glibc...
I searched with google and found some unsolved problem like the one I have.

What I did now is, declare a key[50] static, this works fine.
I still want to make sure what the problem is, though.
Richard


Thanks!

Deephay
Apr 11 '06 #3
Deephay wrote:
Richard Bos wrote:
Deephay <tu*****@gmail. com> wrote:
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 ***
Why not simply use strcspn(&data[m], " \t\r\n")?

I have to get the index where the first "space" locates.


Ok, that would be "strcspn(&d ata[m], " \t\r\n")+1" if there are
any spaces, but you did not add 1 in your code either.
key = realloc(key, p);
strncpy(key, &data[m], p);
key[p] = '\0';

I still want to make sure what the problem is, though.


The last assignment above invokes undefined behavior even if
realloc() did not return NULL.

Ralf
Apr 11 '06 #4

In article <e1***********@ news3.infoave.n et>, Deephay <tu*****@gmail. com> writes:

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 ***
glibc is off-topic for comp.lang.c, but this is glibc telling you
that you have invoked Undefined Behavior. Probably you have
corrupted glibc's housekeeping data by performing an illegal
operation on an object with dynamic storage duration, such as writing
past the end of an allocated area.
and then I inserted a perror("realloc ") to see what happend, it says that:
What will happen is that you will get a meaningless message written
to stderr. realloc does not set errno, so perror will report whatever
happens to have already been in errno.
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);
Wrong for two reasons. You failed to check whether realloc
succeeded, and if it failed, you just lost the old value of "key"
and so introduced a memory leak.

The result of realloc should always be stored in a temporary
variable and should be checked for null. If it is null, remember
to free the old value:

char *newkey;
newkey = realloc(key, p);
if (! newkey)
{
free(key);
[perform error handling]
}
key = newkey;
strncpy(key, &data[m], p);
key[p] = '\0';
You just wrote past the end of the allocated area. Since key is an
area of p bytes, valid indices are 0 through p-1, inclusive.
and the "key" is already malloced before the loop:

char *key = malloc(1);
Did you check to see whether malloc succeeded?
Any suggestion could be helpful, thx very much!


Read the comp.lang.c FAQ (http://www.c-faq.com is one source). Get a
copy of the C standard. C makes little effort to protect you from
yourself; you will only produce reliable, correct C code by learning
the language and its pitfalls.

--
Michael Wojcik mi************@ microfocus.com

The lecturer was detailing a proof on the blackboard. He started to say,
"From the above it is obvious that ...". Then he stepped back and thought
deeply for a while. Then he left the room. We waited. Five minutes
later he returned smiling and said, "Yes, it is obvious", and continued
to outline the proof. -- John O'Gorman
Apr 11 '06 #5
Deephay <tu*****@gmail. com> wrote:
Richard Bos wrote:
Deephay <tu*****@gmail. com> wrote:
p = min(strcspn(&da ta[m], " "),
strcspn(&data[m], "\t"),
strcspn(&data[m], "\r"),
strcspn(&data[m], "\n"));
Why not simply use strcspn(&data[m], " \t\r\n")?

I have to get the index where the first "space" locates.


That one call does the same thing as those four calls plus a properly
written min() function.
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);


Hard to say what the real problem is without any object or function
definitions, but two questions spring to mind:
- does this occur immediately, or after a few iterations;
- what actually is the value of p (and if this code isn't complete, of
key) at the point where it produces the error?

the error occurred after a few iterations, the first realloc will always
success.
the p is always larger than 0, I have tested. Actually it will be a
quite normal value where the error produced, say, 7, 8, or whatever...

What I think now is that it might be a bug of glibc...


That is the last thing I would consider.
I searched with google and found some unsolved problem like the one I have.
You can find a great many confused bug-writers on the 'web, yes, many of
them blaming their tools for their own mistakes.
What I did now is, declare a key[50] static, this works fine.
It probably works around a bug - using strncpy() without thorough
understanding is asking for one, btw - and leaves a time bomb in your
code. What happens if you encounter a token larger than 50 characters?
Worse, what if you encounter one of _precisely_ 50 characters?
I still want to make sure what the problem is, though.


Without more code which demonstrates the problem precisely, it is
impossible to be certain. If the above is your exact code, you have
several off-by-one errors; then again, if the above is your exact code,
it doesn't compile, because there is a lot missing.

If you want more help, what you should do now is the following:
- make a copy of your existing code;
- whittle it down to the smallest _compilable_ program which still
exhibits the same problem;
- post _exactly_ that code. Paste, do not retype it into your post,
otherwise you'll make typos.

Richard
Apr 11 '06 #6
Michael Wojcik wrote:
The result of realloc should always be stored in a temporary
variable and should be checked for null. If it is null, remember
to free the old value:

char *newkey;
newkey = realloc(key, p);
if (! newkey)
{
free(key);
[perform error handling]
}
key = newkey;


Uh? Doesn't realloc(), when it doesn't fail, call free() all by itself
if there's a need for that? Also suppose the reallocated memory doesn't
'move' (newkey == key); doing a "free(key); " now could be disastrous.

--
If you're posting through Google read <http://cfaj.freeshell. org/google>
Apr 11 '06 #7
>Michael Wojcik wrote:
The result of realloc should always be stored in a temporary
variable and should be checked for null. If it is null, remember
to free the old value ...

In article <sl************ *******@ID-203069.user.ind ividual.net>
Pedro Graca <he****@hotpop. com> wrote:Uh? Doesn't realloc(), when it doesn't fail, call free() all by itself
if there's a need for that?
No!

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;
}

(where the "magic" function obtains the size previously malloc()ed,
or the size of the previously malloc()ed region, whichever is
larger, based on "old", or returns 0 if old==NULL).

Note specifically that "old" is *not*, I repeat NOT, free()d if
"new" memory is not obtainable.
Also suppose the reallocated memory doesn't 'move' (newkey == key);


In this case, the return value from realloc() is necessarily not
NULL (well, except if old==NULL).

In both C89 and C99, realloc(p, 0) (where p!=NULL) is equivalent
to free(p). In at least C89 (and perhaps both C89 and C99),
realloc(NULL, 0) does something no one can quite explain. :-)
(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)?)
--
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 11 '06 #8
Pedro Graca schrieb:
Michael Wojcik wrote:
The result of realloc should always be stored in a temporary
variable and should be checked for null. If it is null, remember
to free the old value:

char *newkey;
newkey = realloc(key, p);
if (! newkey)
{
free(key);
[perform error handling]
}
key = newkey;


Uh? Doesn't realloc(), when it doesn't fail, call free() all by itself
if there's a need for that? Also suppose the reallocated memory doesn't
'move' (newkey == key); doing a "free(key); " now could be disastrous.


realloc() returns a null-pointer when it fails, hence the if branch is
only taken after a failure in realloc().
Apr 11 '06 #9
Marc Thrun wrote:
Pedro Graca schrieb:
Michael Wojcik wrote:
The result of realloc should always be stored in a temporary
variable and should be checked for null. If it is null, remember
to free the old value:

char *newkey;
newkey = realloc(key, p);
if (! newkey)
{
free(key);
[perform error handling]
}
key = newkey;


Uh? Doesn't realloc(), when it doesn't fail, call free() all by itself
if there's a need for that? Also suppose the reallocated memory doesn't
'move' (newkey == key); doing a "free(key); " now could be disastrous.


realloc() returns a null-pointer when it fails, hence the if branch is
only taken after a failure in realloc().


Ah! Of course. Thank you.
(sorry Michael)
--
If you're posting through Google read <http://cfaj.freeshell. org/google>
Apr 11 '06 #10

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

Similar topics

36
2849
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
1528
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
4030
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
3890
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
8401
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
7892
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
1856
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
9969
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
9810
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,...
1
10896
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
9612
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
7999
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
7151
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();...
1
4650
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
4251
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3257
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.