Re: Can I Trust Pointer Arithmetic In Re-Allocated Memory?



On Sun, 13 Aug 2006 16:14:19 UTC, "Bill Reid"
<hormelfree@xxxxxxxxxxxxxxxx> wrote:

What I forgot was that if I don't malloc() the block first, if I
realloc() in a loop I get a memory access exception. I hate it
when that happens...

void *p = NULL; /* we have no memory yet */
void *temp; /* realloc will set it */

size_t size = 0; /* we calculate the size in the loop before we call
realloc */
....
for (....) {
....
if ((temp = realloc(p, size) != NULL) {
/* realloc failed */
return NULL; /* or some other error code */
}
p = temp;
....
}
free(p);

will work always - except your implementation is really broken. But
hten trow your compiler into trash and get another one.

Maybe it IS a bug in the compiler, if it wasn't so easy to work
around, I might actually worry about it more. As it is, I did a
search on the compiler maker's web-site for any information
on known bugs, came up with nothing, and left a question on
the discussion forum about it, see if anybody knows anything...

I would say you have forgotten to initialise the pointer given to
realloc with NULL signalling it that thre is currently nothing to
realloc but malloc.

--
Tschau/Bye
Herbert

Visit http://www.ecomstation.de the home of german eComStation
eComStation 1.2 Deutsch ist da!
.



Relevant Pages

  • Re: Can I Trust Pointer Arithmetic In Re-Allocated Memory?
    ... If your compiler ... it works with a cast. ... Pointer arithmetic, as you probably know, is scaled by ... not sure about concerning realloc(). ...
    (comp.lang.c)
  • Re: Problem with realloc (I think)
    ... compiler has a problem with realloc. ... the compiler I'm using is Borland C++ 5.x ... needed multiple realloc calls uses the Windows API memory routines. ... If changing your malloc implementation makes your code work, ...
    (comp.lang.c)
  • Re: Problem with realloc (I think)
    ... compiler has a problem with realloc. ... the compiler I'm using is Borland C++ 5.x ... needed multiple realloc calls uses the Windows API memory routines. ... You might see if your malloc implementation has some debugging options, ...
    (comp.lang.c)
  • Re: Problem with realloc (I think)
    ... compiler has a problem with realloc. ... the compiler I'm using is Borland C++ 5.x ... needed multiple realloc calls uses the Windows API memory routines. ... You might see if your malloc implementation has some debugging options, ...
    (comp.lang.c)
  • Re: Problem with realloc (I think)
    ... If (c>= BUFFERSIZE) then he will be writing a NULL at one past the ... They say it's a poor programmer who blames his compiler, ... compiler has a problem with realloc. ...
    (comp.lang.c)