home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!mcsun!fuug!demos!kiae!glas!demos!cs.cornell.edu!ressler
- From: ressler@cs.cornell.edu
- Newsgroups: comp.lang.c
- Date: 18 Jul 92 08:37 MDT
- Subject: Re: (Help) dynamic use of sprintf ?
- Sender: Notesfile to Usenet Gateway <notes@glas.apc.org>
- Message-ID: <1992Jul18.043753.28919@cs.cornel>
- References: <brself.711345285@hal>
- Nf-ID: #R:brself.711345285@hal:945470687:1992Jul18.043753.28919@cs.cornel:919521842:001:1127
- Nf-From: cs.cornell.edu!ressler Jul 18 08:37:00 1992
- Lines: 30
-
-
- In article <1992Jul17.220700.24800@organpipe.uug.arizona.edu> dave@cs.arizona.edu (Dave Schaumann) writes:
- >In article <brself.711345285@hal>, brself@hal (Ben Self) writes:
- >>Often when formatting strings or converting numerics to alphas, sprintf ()
- >>appears as an extremely attractive possibility. Unfortunately, it does not
- >>fit well with dynamic allocation nor is it easily safe guarded from
- >>segmentation faults and bus errors.
- >
- >[various methods of determining the length of a number's decimal
- >[representation deleted
- >
- >[ Dave's static buffer and copy solution deleted. ]
-
- Another solution that avoids the copy is to malloc big and shrink
- wrap. In TC, sprintf returns the number of characters in the output
- string, so this doesn't even require a strlen():
-
- buf = malloc(MAX_POSSIBLE_SPRINTF_LENGTH);
- len = sprintf(buf, "%d", ...);
- buf = realloc(buf, len+1);
-
- However, some sprintfs do not return this useful value,
- so it's necessary to replace len+1 with strlen(buf)+1.
-
- realloc() is usually very fast when it's shrinking, so this is a
- reasonable way to go.
-
- For a related idea, see GNU's obstack package.
- Gene
-
-