Re: [xml] sprintf and xmlChar



On Mon, Aug 26, 2002 at 10:31:48PM +0200, Christian Stocker wrote:
Can something go awry, if i do the following:

xmlChar *value, *string;
...
value = (xmlChar*) malloc (sizeof(xmlChar *) * (xmlStrlen(string) +
3));
sprintf(value, "\"%s\"", string);
...

or is there a better way of surrounding a xmlChar with " and " (or any
other character...). And can I use sprintf for xmlChar? Maybe I didn't
see something obvious, which would forbid that...

This is bad code.

First, you should cast the string and value pointers to char* before
passing them to sprintf.  Second, the argument to malloc is wrong.
It probably should be simply xmlStrlen(string)+3; multiplying by a
pointer size is useless, and if xmlChar isn't the same size as char,
then the %s wouldn't work anyway.  Finally, malloc is allowed to
fail, so you should be checking for a NULL value before passing it
to sprintf.  (I don't agree with Daniel on the need for snprintf;
we're certain about the string length.)

Nathan Myers




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