Deutsch   English   Français   Italiano  
<87ed8w3025.fsf@nosuchdomain.example.com>

View for Bookmarking (what is this?)
Look up another Usenet article

Path: ...!feed.opticnetworks.net!eternal-september.org!feeder3.eternal-september.org!news.eternal-september.org!.POSTED!not-for-mail
From: Keith Thompson <Keith.S.Thompson+u@gmail.com>
Newsgroups: comp.lang.c
Subject: Re: Whaddaya think?
Date: Sun, 16 Jun 2024 17:06:10 -0700
Organization: None to speak of
Lines: 38
Message-ID: <87ed8w3025.fsf@nosuchdomain.example.com>
References: <666ded36$0$958$882e4bbb@reader.netnews.com>
	<20240616015649.000051a0@yahoo.com> <v4lm16$3s87h$4@dont-email.me>
	<v4lmso$3sl7n$1@dont-email.me> <v4lr0m$3tbpj$1@dont-email.me>
	<8734pd4g3s.fsf@nosuchdomain.example.com>
	<v4ltuj$3trj2$1@dont-email.me>
MIME-Version: 1.0
Content-Type: text/plain
Injection-Date: Mon, 17 Jun 2024 02:06:11 +0200 (CEST)
Injection-Info: dont-email.me; posting-host="a34467dd4a85130cbe55ab07dc34e4ee";
	logging-data="313326"; mail-complaints-to="abuse@eternal-september.org";	posting-account="U2FsdGVkX19bKuZeZ2aoI+GqmxWeAPmp"
User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/27.2 (gnu/linux)
Cancel-Lock: sha1:3QrgZ4na2g6hycKBrr5eHgC4Nr8=
	sha1:Rv2iQLlZSpASagslrOXaYhl9YPs=
Bytes: 2448

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.com
void Void(void) { Void(); } /* The recursive call of the void */