Potential negative index access in one of the sample codes

Description

In `icu4c/source/samples/ufortune.c`, `time(NULL)` is used to create a random number (Line 196), with explicit cast to `int` on it.
However, this code segment is potentially buggy, since `time()` returns a 64-bit signed integer (time_t) and casting this to `int` creates a negative number.
This later exits the application since passing a negative index to `ures_getStringByIndex()` returns a NULL with error code `U_MISSING_RESOURCE_ERROR`.

To fix this, it is better to not cast the return value of `time()` to `int`, since we know that size of variable i does not exceed `numFortune`.

```
...
if (numFortunes <= 0) {
fprintf(stderr, "%s: no fortunes found.\n", programName);
exit(-1);
}

i = (int)time(NULL) % numFortunes; /* Use time to pick a somewhat-random fortune. */
resString = ures_getStringByIndex(fortunes_r, i, &len, &err);
if (U_FAILURE(err)) {
fprintf(stderr, "%s: ures_getStringByIndex(%d) failed, %s\n", programName, i, u_errorName(err));
exit(-1);
}
...
```

Status

Assignee

Steven R. Loomis

Reporter

Keita Suzuki

Labels

None

Reviewer

None

Time Needed

None

Start date

None

Components

Fix versions

Priority

minor
Configure