[Xorp-cvs] XORP cvs commit: xorp/libxorp
Atanu Ghosh
atanu@ICSI.Berkeley.EDU
Tue, 20 Dec 2005 23:57:10 -0800
--=-=-=
I have attached my test program. If you remove the calls to va_copy and
run it on xorp13 you will see the problem,
--=-=-=
Content-Type: text/x-c
Content-Disposition: attachment; filename=pr.c
Content-Description: varags test program
#include <stdio.h>
#include <stdarg.h>
int
x_vasprintf(char **ret, const char *format, va_list ap)
{
size_t i, buf_size = 1024 + 1;
char *buf_ptr = NULL;
int ret_size;
#ifdef va_copy
va_list temp;
#endif
for (i = 0; i < 3; i++) {
/*
* XXX: two iterations should be sufficient to compute the
* buffer size and allocate it, but anyway we try one more time
*/
buf_ptr = malloc(buf_size);
if (buf_ptr == NULL)
break; /* Cannot allocate memory */
buf_ptr[0] = '\0';
#ifdef va_copy
va_copy(temp, ap);
ret_size = vsnprintf(buf_ptr, buf_size, format, temp);
#else
ret_size = vsnprintf(buf_ptr, buf_size, format, ap);
#endif
if (ret_size < 0)
break; /* Cannot format the string */
if ((size_t)ret_size < buf_size) {
*ret = buf_ptr;
return (ret_size);
}
/* The allocated buffer was too small. Try again. */
free(buf_ptr);
buf_ptr = NULL;
buf_size = ret_size + 1; /* XXX: include space for trailing '\0' */
}
/*
* Error: cannot format the string or cannot allocate enough memory
*/
if (buf_ptr != NULL)
free(buf_ptr);
*ret = NULL;
return (-1);
}
int
x_asprintf(char **ret, const char *format, ...)
{
va_list ap;
int ret_size;
va_start(ap, format);
ret_size = x_vasprintf(ret, format, ap);
va_end(ap);
return (ret_size);
}
int
main(int argc, char **argv)
{
char *ptr;
char buf[21060];
int i;
for(i = 0; i < sizeof(buf); i++)
buf[i] = 's';
buf[sizeof(buf) - 1] = 0;
x_asprintf(&ptr, "%s\n", buf);
if (0 == ptr)
printf("bad news\n");
else
printf(ptr);
return 0;
}
--=-=-=
Atanu.
--=-=-=--