[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
On Tue, 30 Apr 2002, Hansen Martin wrote:
> I had a hard time getting used to char*
> When I had to construct a new string I was forced to guess the size
> beforehand, so I could malloc the space
> char* s;
> size_t size;
> But the I discovered asprintf that automatically allocates space for a
> string, so now I could:
> char* s;
> But I cant compile this GNU function with cris ;o((
> Any suggestions?
I don't know what "asprintf" is, but you can get the required space by using
snprintf with a buffer-size of 0. It returns the number of characters which
would have been written if there was a buffer, and you can use that value to
malloc the string and do a "real" snprintf on it. See "man snprintf" under
the Return value section.
You could also make an educated guess of the size and use snprintf and if it
does not fit, it is truncated and that might be good enough for you
NEVER under any circumstances use sprintf though... (for the reason you
noted - you don't know if it will overflow your buffer or not, with snprintf
you at least don't corrupt your program if you guess incorrectly..).
- From: Hansen Martin <DKDD0MAR@xxxxxxx.com>