Sujet : Re: Whaddaya think?
De : janis_papanagnou+ng (at) *nospam* hotmail.com (Janis Papanagnou)
Groupes : comp.lang.cDate : 17. Jun 2024, 06:48:39
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <v4oinp$gpg0$1@dont-email.me>
References : 1 2 3 4 5 6 7 8
User-Agent : Mozilla/5.0 (X11; Linux x86_64; rv:45.0) Gecko/20100101 Thunderbird/45.8.0
On 17.06.2024 02:06, Keith Thompson wrote:
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.
No, I didn't assume that. I just missed that 'anchor' will get lost.
Thanks!
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. [...]
Yes, that was certainly the case. (I did no thorough test with large
data sets, just a simple ad hoc test.)
Elsethread I suggested to merge the malloc() with the realloc() call.
The resulting code would be simpler (and might address that problem).
int chunk = 10;
int bufsize = 1;
char * anchor = NULL;
while ((anchor = realloc (anchor, bufsize += chunk)) != NULL &&
fgets (anchor+bufsize-chunk-1, chunk+1, stdin) != NULL)
;
puts (anchor);
Do you see the exposed problem (or any other issues) here, too?
Janis