I am writing a rotate string function in C. The intended behavior is that the strings chars will be rotated using a modulus of the string length, and a key. The function seems to work in the forward direction, but if I specify a negative key, I want the string to rotate in the opposite direction, and this is where the bug exists. For completeness/testing purposes, I will supply the entire program, but below that I will highlight the problem area and explain what I've done to try to debug so far:
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <string.h>
char *rotate_str(char *mutable_str, int key);
int main(void) {
char str[] = "This is a test.";
char *output = rotate_str(str, -2);
printf("%s\n", output);
return EXIT_SUCCESS;
}
//Bug - negative rotate doesn't work properly - test with -2
char *rotate_str(char *mutable_str, int key) {
assert(mutable_str);
size_t len = strlen(mutable_str);
ssize_t i;
char *output = malloc(len + 1);
assert(output);
ssize_t rotated_index = 0;
for (i = 0; i < len; ++i) {
rotated_index = (i + key) % len; // Get the new index position
output[rotated_index] = mutable_str[i];
}
output[len] = '\0';
return output;
}
The trouble spot is:
for (i = 0; i < len; ++i) {
rotated_index = (i + key) % len; // Get the new index position
output[rotated_index] = mutable_str[i];
}
On the first iteration, i = 0
, key = -2
, and len = 15
. When I compute -2 + 0 % 15
using a calculator (Google in this case), I get 13
. However, my C program is making rotated_index = 14
as per my debugger output. So this itself is already a concern.
When I do a positive 2
as key
, I get output: t.This is a tes
, which is what I'd expect. But when I do the -2
as key
, I get output: is is a test.
but the expected output is is is a test.Th