qdist: return "(empty)" instead of NULL when printing an empty dist

Printf'ing a NULL string is undefined behaviour. Avoid it.

Reported-by: Peter Maydell <peter.maydell@linaro.org>
Signed-off-by: Emilio G. Cota <cota@braap.org>
Message-Id: <1469459025-23606-4-git-send-email-cota@braap.org>
Signed-off-by: Paolo Bonzini <pbonzini@redhat.com>
This commit is contained in:
Emilio G. Cota 2016-07-25 11:03:45 -04:00 committed by Paolo Bonzini
parent 071d405477
commit 11b7b07f8a
2 changed files with 12 additions and 4 deletions

View File

@ -360,10 +360,16 @@ static void test_none(void)
g_assert(isnan(qdist_xmax(&dist))); g_assert(isnan(qdist_xmax(&dist)));
pr = qdist_pr_plain(&dist, 0); pr = qdist_pr_plain(&dist, 0);
g_assert(pr == NULL); g_assert_cmpstr(pr, ==, "(empty)");
g_free(pr);
pr = qdist_pr_plain(&dist, 2); pr = qdist_pr_plain(&dist, 2);
g_assert(pr == NULL); g_assert_cmpstr(pr, ==, "(empty)");
g_free(pr);
pr = qdist_pr(&dist, 0, QDIST_PR_BORDER);
g_assert_cmpstr(pr, ==, "(empty)");
g_free(pr);
qdist_destroy(&dist); qdist_destroy(&dist);
} }

View File

@ -14,6 +14,8 @@
#define NAN (0.0 / 0.0) #define NAN (0.0 / 0.0)
#endif #endif
#define QDIST_EMPTY_STR "(empty)"
void qdist_init(struct qdist *dist) void qdist_init(struct qdist *dist)
{ {
dist->entries = g_new(struct qdist_entry, 1); dist->entries = g_new(struct qdist_entry, 1);
@ -233,7 +235,7 @@ char *qdist_pr_plain(const struct qdist *dist, size_t n)
char *ret; char *ret;
if (dist->n == 0) { if (dist->n == 0) {
return NULL; return g_strdup(QDIST_EMPTY_STR);
} }
qdist_bin__internal(&binned, dist, n); qdist_bin__internal(&binned, dist, n);
ret = qdist_pr_internal(&binned); ret = qdist_pr_internal(&binned);
@ -308,7 +310,7 @@ char *qdist_pr(const struct qdist *dist, size_t n_bins, uint32_t opt)
GString *s; GString *s;
if (dist->n == 0) { if (dist->n == 0) {
return NULL; return g_strdup(QDIST_EMPTY_STR);
} }
s = g_string_new(""); s = g_string_new("");