[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: asprintf



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;
> size=guesize();
> malloc(size);
> sprintf(s,"qwerty")
> 
> 
> But the I discovered asprintf that automatically allocates space for a
> string, so now I could:
> 
> char* s;
> sprintf(&s,"qwerty")
> 
> But I cant compile this GNU function with cris ;o((
> Any suggestions?

Hi,

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 
sometimes.

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..).

/BW