Re: adapting getline



Richard <rgrdev_@xxxxxxxxx> writes:

James Kuyper <jameskuyper@xxxxxxxxxxx> writes:

kid joe wrote:
On Mon, 20 Apr 2009 02:10:23 +0100, Ben Bacarisse wrote:
Franken Sense <frank@xxxxxxxxxxxxxxx> writes:
buf = realloc(buf, ++bufsz);
This only works if realloc never fails.

Hi Ben,

In practise realloc never fails in this situation as the amount of memory
involved is very small. Even if it does fail, then the next line

*(buf + bufsz - 1) = c;

will detect the error automatically and exit the program with an error
message, so there's no danger of data corruption.

No, such code is NOT guaranteed to detect the error automatically. The
behavior is undefined. There is a popular notion that "undefined
behavior" means that your program will exit immediately. That is a

I suspect he means on his system.

His code won't work, reliably, on many systems. For some reason he
picked only one comment to talk about. The code is wrong for reasons
other than just the realloc assumption.

--
Ben.
.



Relevant Pages

  • Re: adapting getline
    ... This only works if realloc never fails. ... It's a commonplace result, because essentially random addresses have a good chance, on many systems, of being addresses of memory your program doesn't have a right to modify, and attempting to write to such memory causes the program to abort. ... after a failed reallocation, the objects that the expression buf + bufsz - 1 could, in principle, point at, include fd, buf, c, and bufsize, or a piece of memory from a previous successful reallocation. ...
    (comp.lang.c)
  • Re: Increase memory buffer with realloc or malloc?
    ... A realloc() that fails if the memory buffer cannot be enlarged without ... This is especially true if the memory chunk is over ...
    (comp.lang.c)
  • Re: when can realloc fail?
    ... But a call to realloc() with size set to zero is equivalent to free, ... All we're told is that realloceither fails or it ...
    (comp.lang.c)
  • Re: Memory leaks with realloc()
    ... > a memory leak anywhere in this code? ... valid pointer `a->number' with NULL. ... realloc() fails you call `exit'. ...
    (comp.lang.c)
  • Re: [C] please critique my code
    ... If realloc() fails, it returns a NULL pointer, and leaves the old buffer ... a.c.l.l.c-c++ FAQ: http://www.comeaucomputing.com/learn/faq ...
    (alt.comp.lang.learn.c-cpp)