1753720 Members
4790 Online
108799 Solutions
New Discussion

realloc() error

 
SOLVED
Go to solution
Scott Van Kalken
Esteemed Contributor

realloc() error

Hey all,

does anyone have any information (other than man pages) or experience with realloc() failing on HPUX
11.00? 32Bit and 64Bit

This problem occurs under both gcc and ansiC.


for (i = 0; i < 3; i++) {
if ((varspace[i] = (struct VSPACE *)realloc(varspace[i],sizeof(s
truct VSPACE))) == NULL) {
perror("malloc(1)");
exit(1);
}
memset((char *)varspace[i], 0, (int)sizeof(varspace[i]));
}



This is a tiny snippet of the offending code.


A dump file (sort of tracing what program does) comes out with the following:

Begin: {(173) END: }(175)
[1]#(43)[1]S(123)[1]:(72)[1]n(156)[1]a(141)[1]m(155)[1]e(145)[1]2(62)[1]:(72)[1]
"(42)[1] (40)[1]"(42)[1]:(72)[1]1(61)[1]:(72)[1]0(60)[1] (40)[1]}(175)


STRINGPROCESS FUNCTION
Stdup string is 1074305086 and end is 1074305103
(#S:name2:" ":1:0 )

which is normal (for what this program does).

Has anyone had any problems with realloc()?

Scott.

1 REPLY 1
A. Clay Stephenson
Acclaimed Contributor
Solution

Re: realloc() error

Hi Scott:

I've regularly used realloc() and had no problems like you describe. I did note that in your code snippet varspace[i] was undefined in the call to realloc. I assume in the real code that initially varspace[i] is NULL so that realloc can revert to malloc behavior.

The other thing that can really create havoc is the case where you initially malloc or calloc or realloc a space that has pointers pointing within the allocated space. Now consider the case where you then use realloc to expand the original space. If realloc is able to expand in place (as it often does) then no worries; however, if realloc cannot expand in place it creates a new space and copies the contents of the old space to the new space and the old space is returned to the heap. Pointers which still refer to addresses within the old space now point to the Twilight Zone.

Food for thought, Clay
If it ain't broke, I can fix that.