Path: csiph.com!news.swapon.de!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, 24 Jun 2024 02:55:39 -0700 Organization: None to speak of Lines: 41 Message-ID: <875xtyu0kk.fsf@nosuchdomain.example.com> References: MIME-Version: 1.0 Content-Type: text/plain Injection-Date: Mon, 24 Jun 2024 11:55:40 +0200 (CEST) Injection-Info: dont-email.me; posting-host="0a690d6294358a2c4bce5879f14e083a"; logging-data="921546"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1/jIJt8cubpkcQgjAPAGOsS" User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/27.2 (gnu/linux) Cancel-Lock: sha1:xwGQX65ed2O+vwImQ/DajeUTBhk= sha1:6GxzpYfw4wQ+bbtMZavOdo1a3u8= Xref: csiph.com comp.lang.c:386446 Lawrence D'Oliveiro writes: > On Fri, 21 Jun 2024 21:12:12 +0200, Bonita Montero wrote: >> Usually you don't resize the block with a few bytes ... > > The usual way I use realloc is to maintain separate counts of the number > of array elements I have allocated, and the number I am actually using. A > realloc call is only needed when the latter hits the former. Every time I > call realloc, I will extend by some minimum number of array elements (e.g. > 128), roughly comparable to the sort of array size I typically end up > with. > > And then when the structure is complete, I do a final realloc call to > shrink it down so the size is actually that used. Is it safe to assume > such a call will never fail? Hmm ... It's not safe to assume that a shrinking realloc call will never fail. It's possible that it will never fail in any existing implementation, but the standard makes no such guarantee. A (perhaps) plausible way it can fail is if allocations of different sizes are allocated from different pools. Trying to shrink a 1000-byte object to 100 bytes might fail if the 100-byte pool has been exhausted. On the other hand, realloc() could just return its argument in such a case and continue treating the object as a 1000-byte allocation. (The allocation functions don't have to keep track of how much memory you asked for, only how much they actually allocated, which is >= what you asked for.) Arguably only a poor implementation would fail on a shrinking realloc(), but the standard permits poor implementations. Having said all that, if realloc fails (indicated by returning a null pointer), you still have the original pointer to the object. Something else that occurs to me: If a shrinking realloc() never fails in practice, then any code you write to handle a failure won't be tested. -- Keith Thompson (The_Other_Keith) Keith.S.Thompson+u@gmail.com void Void(void) { Void(); } /* The recursive call of the void */