Sujet : Re: Whaddaya think?
De : Keith.S.Thompson+u (at) *nospam* gmail.com (Keith Thompson)
Groupes : comp.lang.cDate : 17. Jun 2024, 01:06:10
Autres entêtes
Organisation : None to speak of
Message-ID : <87ed8w3025.fsf@nosuchdomain.example.com>
References : 1 2 3 4 5 6 7
User-Agent : Gnus/5.13 (Gnus v5.13) Emacs/27.2 (gnu/linux)
Janis Papanagnou <janis_papanagnou+
ng@hotmail.com> writes:
[...]
#include <stdlib.h>
#include <stdio.h>
>
void main (int argc, char * argv[])
{
int chunk = 10;
int bufsize = chunk+1;
char * buf = malloc(bufsize);
char * anchor = buf;
while (fgets(buf, chunk+1, stdin) != NULL)
if (realloc(anchor, bufsize += chunk) != NULL)
buf += chunk;
puts(anchor);
}
realloc() can return the pointer you pass to it if there's enough room
in the existing location. (Or it can relocate the buffer even if there
is enough room.)
But if realloc() moves the buffer (copying the existing data to it), it
returns a pointer to the new location and invalidates the old one. You
discard the new pointer, only comparing it to NULL.
Perhaps you assumed that realloc() always expands the buffer in place.
It doesn't.
If the above program worked for you, I suspect that either realloc()
never relocated the buffer, or you continued using the original buffer
(and beyond) after realloc() invalidated it.
The worst consequence of undefined behavior is having your code appear
to "work".
-- Keith Thompson (The_Other_Keith) Keith.S.Thompson+u@gmail.comvoid Void(void) { Void(); } /* The recursive call of the void */