strlen
returns a size_t
(unsigned-related) variable, and before any comparision, both variables must have the same type. So, one of them must be cast to the other.
In your example, I'm sure to
has been casted to unsigned
, causing overflow (-1), and probably, you are comparing strlen(string)
to the max representable unsigned integer (the probable result of the overflow).
So, the solution is:
char *str_sub(char *string, int from, int to) {
assert(to < 0 || from < to);
if (!(to < (int)strlen(string))) {
printf("%d %ld\n", to, strlen(string));
}
assert(from < strlen(string) && to < (int)strlen(string));
char *result = (char *) calloc(to - from + 1, 1);
memcpy(result, &string[from], to);
result[to] = '\0';
Or, to avoid recalculations:
char *str_sub(char *string, int from, int to) {
int length = strlen(string);
assert(to < 0 || from < to);
if (!(to < length)) {
printf("%d %ld\n", to, length);
}
assert(from < length && to < length);
char *result = (char *) calloc(to - from + 1, 1);
memcpy(result, &string[from], to);
result[to] = '\0';
Or, to do safe castings, for too long string
s (thanks for remarking it, @chux):
char *str_sub(char *string, int from, int to) {
size_t length = strlen(string);
assert(length > 0);
assert(to < 0 || from < to);
if (!(to > 0 && to < length))
printf("%d %lu\n", to, length);
assert(from < length);
assert(to < 0 || to < length);
char *result = (char *) calloc(to - from + 1, 1);
memcpy(result, &string[from], to);
result[to] = '\0';