diff --git a/src/kernel/reports.c b/src/kernel/reports.c index a7244d213..8fb83abd7 100644 --- a/src/kernel/reports.c +++ b/src/kernel/reports.c @@ -1858,8 +1858,9 @@ const char *trailinto(const region * r, const struct locale *lang) size_t f_regionid(const region * r, const faction * f, char *buffer, size_t size) { + size_t len; if (!r) { - strncpy(buffer, "(Chaos)", size); + len = strlcpy(buffer, "(Chaos)", size); } else { plane *pl = rplane(r); const char *name = pl ? pl->name : 0; @@ -1867,12 +1868,12 @@ f_regionid(const region * r, const faction * f, char *buffer, size_t size) int named = (name && name[0]); pnormalize(&nx, &ny, pl); adjust_coordinates(f, &nx, &ny, pl, r); - strncpy(buffer, rname(r, f->locale), size); - buffer[size - 1] = 0; - sprintf(buffer + strlen(buffer), " (%d,%d%s%s)", nx, ny, named ? "," : "", - (named) ? name : ""); + len = strlcpy(buffer, rname(r, f?f->locale:0), size); + snprintf(buffer + len, size-len, " (%d,%d%s%s)", nx, ny, named ? "," : "", (named) ? name : ""); + buffer[size-1] = 0; + len=strlen(buffer); } - return strlen(buffer); + return len; } static char *f_regionid_s(const region * r, const faction * f) diff --git a/src/kernel/reports_test.c b/src/kernel/reports_test.c index 29bc9f5d2..d07217ece 100644 --- a/src/kernel/reports_test.c +++ b/src/kernel/reports_test.c @@ -52,9 +52,32 @@ static void test_reorder_units(CuTest * tc) CuAssertPtrEquals(tc, 0, u0->next); } +static void test_regionid(CuTest * tc) { + size_t len; + const struct terrain_type * plain; + struct region * r; + char buffer[64]; + + test_cleanup(); + plain = test_create_terrain("plain", 0); + r = test_create_region(0, 0, plain); + + memset(buffer, 0xff, sizeof(buffer)); + len = f_regionid(r, 0, buffer, sizeof(buffer)); + CuAssertIntEquals(tc, 11, len); + CuAssertStrEquals(tc, "plain (0,0)", buffer); + + memset(buffer, -1, sizeof(buffer)); + len = f_regionid(r, 0, buffer, 11); + CuAssertIntEquals(tc, 10, len); + CuAssertStrEquals(tc, "plain (0,0", buffer); + CuAssertIntEquals(tc, -1, buffer[11]); +} + CuSuite *get_reports_suite(void) { CuSuite *suite = CuSuiteNew(); SUITE_ADD_TEST(suite, test_reorder_units); + SUITE_ADD_TEST(suite, test_regionid); return suite; }