Path: ...!3.eu.feeder.erje.net!feeder.erje.net!eternal-september.org!feeder3.eternal-september.org!news.eternal-september.org!.POSTED!not-for-mail From: Keith Thompson Newsgroups: comp.lang.c Subject: Re: realloc() - frequency, conditions, or experiences about relocation? Date: Mon, 17 Jun 2024 16:39:38 -0700 Organization: None to speak of Lines: 36 Message-ID: <87h6dr16md.fsf@nosuchdomain.example.com> References: <875xu8vsen.fsf@bsb.me.uk> <87zfrjvqp6.fsf@bsb.me.uk> MIME-Version: 1.0 Content-Type: text/plain Injection-Date: Tue, 18 Jun 2024 01:39:39 +0200 (CEST) Injection-Info: dont-email.me; posting-host="aed299878570cb32e21d076f9aa05b90"; logging-data="1021804"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX18vKDNGLP35MD0XerET/ycB" User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/27.2 (gnu/linux) Cancel-Lock: sha1:GkmtLc3j2YrjEpiDJo0z/fcUCxc= sha1:Wj3JtfDwnhVNU2WpzKIMs699QaM= Bytes: 2737 Malcolm McLean writes: [...] > We have a continuously growing buffer, and we want the best strategy > for reallocations as the stream of characters comes at us. So, given > we now how many characters have arrived, can we predict how many will > arrive, and therefore ask for the best amount when we reallocate, so > that we neither make too many reallocation (reallocate on every byte > received) or ask for too much (demand SIZE_MAX memory when the first > byte is received).? [...] That's going to depend on the behavior of the implementations realloc() function. malloc() and realloc() typically allocate more memory than they're asked for, so that another realloc() call can often expand the allocated memory in place. I have a small test program that uses realloc() to expand a 1-byte allocated buffer to 2 bytes, then 3, then 4, and so on. In one implementation, in one test run, it reallocates at 25 bytes, and then not again until just over 128 kbytes. Other implementations behave differently. A realloc() call that's able to return its first argument is likely to be much quicker than one that does an actual reallocation. If you want to fine tune for performance, you'll have to allow for the implementation you're using, either by performing run-time measurements or by analyzing the implementation (which could change in the next release). Multiplying the size by 2 or 1.5 as needed is likely to be good enough. -- Keith Thompson (The_Other_Keith) Keith.S.Thompson+u@gmail.com void Void(void) { Void(); } /* The recursive call of the void */