Path: ...!feed.opticnetworks.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: Tue, 25 Jun 2024 03:05:16 -0700 Organization: None to speak of Lines: 47 Message-ID: <87frt1tk0z.fsf@nosuchdomain.example.com> References: <875xtyu0kk.fsf@nosuchdomain.example.com> MIME-Version: 1.0 Content-Type: text/plain; charset=utf-8 Content-Transfer-Encoding: 8bit Injection-Date: Tue, 25 Jun 2024 12:05:17 +0200 (CEST) Injection-Info: dont-email.me; posting-host="e9e079a2606fcbb785c539789babdee9"; logging-data="1590333"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1/guWwMHt4SmVzDjLwP94s1" User-Agent: Gnus/5.13 (Gnus v5.13) Cancel-Lock: sha1:z18aROCIPMeUysn79DVQL39q2oM= sha1:2krSndj9/uKwBsXbT5vkJmOPaSE= Bytes: 3305 Lawrence D'Oliveiro writes: > On Mon, 24 Jun 2024 02:55:39 -0700, Keith Thompson wrote: >> Lawrence D'Oliveiro writes: >>> 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. >> >> ... >> >> Having said all that, if realloc fails (indicated by returning a null >> pointer), you still have the original pointer to the object. > > In other words, it’s safe to ignore any error from that last shrinking > realloc? That’s good enough for me. ;) What? No, that's not what I said at all. Suppose you do something like: some_type *p = malloc(BIG_VALUE); // ... p = realloc(p, SMALL_VALUE); If the realloc() succeeds and doesn't relocate and copy the object, you're fine. If realloc() succeeds and *does* relocate the object, p still points to memory that has now been deallocated, and you don't have a pointer to the newly allocated memory. If realloc() fails, it returns a null pointer, but the original memory is still valid -- but again, the assignment clobbers your only pointer to it. I presume you can write code that handles all three possibilities, but you can't just ignore any errors. -- Keith Thompson (The_Other_Keith) Keith.S.Thompson+u@gmail.com void Void(void) { Void(); } /* The recursive call of the void */