1162852Sdes/*
2162852Sdes * Copyright (c) 2005 Darren Tucker
3162852Sdes * Copyright (c) 2005 Damien Miller
4162852Sdes *
5162852Sdes * Permission to use, copy, modify, and distribute this software for any
6162852Sdes * purpose with or without fee is hereby granted, provided that the above
7162852Sdes * copyright notice and this permission notice appear in all copies.
8162852Sdes *
9162852Sdes * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10162852Sdes * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11162852Sdes * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12162852Sdes * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13162852Sdes * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14162852Sdes * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15162852Sdes * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16162852Sdes */
17162852Sdes
18162852Sdes#define BUFSZ 2048
19162852Sdes
20162852Sdes#include <sys/types.h>
21162852Sdes#include <stdlib.h>
22162852Sdes#include <stdio.h>
23162852Sdes#include <stdarg.h>
24162852Sdes#include <string.h>
25162852Sdes
26162852Sdesstatic int failed = 0;
27162852Sdes
28162852Sdesstatic void
29162852Sdesfail(const char *m)
30162852Sdes{
31162852Sdes	fprintf(stderr, "snprintftest: %s\n", m);
32162852Sdes	failed = 1;
33162852Sdes}
34162852Sdes
35162852Sdesint x_snprintf(char *str, size_t count, const char *fmt, ...)
36162852Sdes{
37162852Sdes	size_t ret;
38162852Sdes	va_list ap;
39162852Sdes
40162852Sdes	va_start(ap, fmt);
41162852Sdes	ret = vsnprintf(str, count, fmt, ap);
42162852Sdes	va_end(ap);
43162852Sdes	return ret;
44162852Sdes}
45162852Sdes
46162852Sdesint
47162852Sdesmain(void)
48162852Sdes{
49162852Sdes	char b[5];
50162852Sdes	char *src;
51162852Sdes
52162852Sdes	snprintf(b,5,"123456789");
53162852Sdes	if (b[4] != '\0')
54162852Sdes		fail("snprintf does not correctly terminate long strings");
55162852Sdes
56162852Sdes	/* check for read overrun on unterminated string */
57162852Sdes	if ((src = malloc(BUFSZ)) == NULL) {
58162852Sdes		fail("malloc failed");
59162852Sdes	} else {
60162852Sdes		memset(src, 'a', BUFSZ);
61162852Sdes		snprintf(b, sizeof(b), "%.*s", 1, src);
62162852Sdes		if (strcmp(b, "a") != 0)
63162852Sdes			fail("failed with length limit '%%.s'");
64162852Sdes	}
65162852Sdes
66162852Sdes	/* check that snprintf and vsnprintf return sane values */
67162852Sdes	if (snprintf(b, 1, "%s %d", "hello", 12345) != 11)
68162852Sdes		fail("snprintf does not return required length");
69162852Sdes	if (x_snprintf(b, 1, "%s %d", "hello", 12345) != 11)
70162852Sdes		fail("vsnprintf does not return required length");
71162852Sdes
72162852Sdes	return failed;
73162852Sdes}
74