Article View: comp.lang.c.moderated
Article #2449Re: void* type
From: J. Kanze
Date: Mon, 01 Apr 1996 13:20
Date: Mon, 01 Apr 1996 13:20
51 lines
2706 bytes
2706 bytes
In article <4jmcnr$lr2@solutions.solon.com> stanr@tiac.net (Stan
Ryckman) writes:
|> In article <4jibl5$89u@solutions.solon.com>,
|> J. Kanze <kanze@gabi-soft.fr> wrote:
|> >BTW, I've found that a small optimizing trick in functions like this can
|> >sometimes work wonders for performance:
|> >
|> > int
|> > swap( void* a , void* b , size_t sz )
|> > {
|> > unsigned char buffer[ EXPECTEDMAXSIZE ] ;
|> > void* tmp = (sz <= sizeof( buffer ))
|> > ? buffer
|> > : malloc( sz ) ;
|> Or, if you don't need reentrant or resursive code, you can do:
|> static void *tmp = NULL;
|> static size_t tmp_sz = 0;
|> if (sz > tmp_sz) {
|> .... use realloc here .... you get the idea ....
I wish I'd have thought of this when I actually encountered the problem.
In the real case, the original author of the function had used multiple
returns, and I had a bit of a job finding all of the places where I had
to insert the `free'. (The original code simply overwrote the rest of
the stack if sz were larger than EXPECTEDMAXSIZE. Which sort of
explains why I was looking at it in the first place:-).)
|> Details left to the reader (I'm feeling lazy tonight :)
|> This avoids having to guess what EXPECTEDMAXSIZE might be,
|> but also suffers from never freeing that buffer. OTOH, it might
|> end up avoiding zillions of calls to malloc if the guess was poor.
|> I've had a couple of thing like that bite when data formats
|> were changed, and I had code inherited from people long-gone.
|> The realloc can certainly do something like use sz+10000
|> to "grow" the tmp area in tunable chunks, depending on the application.
Better yet: unless memory is really tight, have it double the size.
This will set a fairly reasonable upper bound on the number of reallocs
you will have to do.
--
James Kanze (+33) 88 14 49 00 email: kanze@gabi-soft.fr
GABI Software, Sarl., 8 rue des Francs Bourgeois, 67000 Strasbourg, France
Conseils en informatique industrielle --
-- Beratung in industrieller Datenverarbeitung
Technical Details
Message-ID:
<4jol6e$1rr@solutions.solon.com>Path:
arc1-ca.pugleaf.net!solon.com!not-for-mailReferences:
<4iepre$ag7@solutions.solon.com> <4ja3qf$p9b@solutions.solon.com> <4jckqc$a5o@solutions.solon.com> <4jibl5$89u@solutions.solon.com>Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!solon.com!not-for-mail From: kanze@gabi-soft.fr (J. Kanze) Newsgroups: comp.lang.c.moderated Subject: Re: void* type Date: 1 Apr 1996 07:20:14 -0600 Organization: GABI Software, Sarl. Sender: clc@solutions.solon.com Approved: clc@solutions.solon.com Message-ID: <4jol6e$1rr@solutions.solon.com> References: <4iepre$ag7@solutions.solon.com> <4ja3qf$p9b@solutions.solon.com> <4jckqc$a5o@solutions.solon.com> <4jibl5$89u@solutions.solon.com> NNTP-Posting-Host: solutions.solon.com