#: 19554 S12/OS9/68000 (OSK)
01-Jan-94 20:31:30
Sb: realloc is broken
Fm: Bob van der Poel 76510,2203
To: All
A little while ago I posted a message suggesting that the realloc() function in
the MW C library might be broken. I wrote the following program to prove it one
way or another...yup, it is broke. I have not tested this with gcc or with
ultra (anyone?). The problem is that when the memory request fails and a NULL
pointer is returned the old memory should NOT be deallocated. In this case it
is. The "b=*bstart" causes a bus error (#102) on a machine protected with SSM.
If you don't have SSM don't feel safe...since the buffer has been deallocated
(memory returned to the system) other processes can now write over your buffer.
I suggest that you either don't use realloc() or do an immediate exit if it
fails or at the least mark the original memory as no longer avaiable. I had the
problem occur in one issue of Ved which I figured I was being very clever in by
using realloc(). I have now switched to the more sedate method of expanding the
buffer by always grabbing an entire new block of memory and copying the old
stuff into it. This is what realloc() does...but sometimes realloc() can just
expand the buffer and skip the copy. Feel free to cross-post this elsewhere if
you think it useful.
#include
main()
{
char *bstart, *newbuf;
char b;
unsigned int t;
for(t=1024, bstart=NULL; t<0xffffffff; t<<=1)
{
printf("bsize=%08x ",t);
newbuf=(char *)realloc(bstart, t);
if(newbuf)
{
bstart=newbuf;
putchar('\n');
}
else
{
b=*bstart; /* try to access OLD buffer area */
puts("ALLOCATION FAILURE");
exit(0);
}
}
}
|