I made a program that reverses a string in C, it's working fine, but I keep getting memory trash when I print the result. I tried this:
That's my program:
#include <stdio.h>
#include <string.h>
#define SIZE_STRING 20
void reverse_string(char* string, int len);
int main() {
char string_test[SIZE_STRING];
printf("What's the string? ");
fgets(string_test, SIZE_STRING, stdin);
string_test[strlen(string_test) - 1] = '\n';
reverse_string(string_test, strlen(string_test) - 1);
printf("The new string is: %s", string_test);
return 0;
}
void reverse_string(char* string, int len){
char str_copy[len];
int i, j;
for(i = 0, j = len - 1; i < len; i++, j--)
{
str_copy[i] = string[j];
}
str_copy[len] = '\n';
strcpy(string, str_copy);
}
A few issues ...
Issues in
main:reverse_string(i.e. both decrement length by 1)Issues in
reverse_string:\ninstead of 0x00 -- this is what causes "trash characters" to appear at the end.i < len, usingi < jis a bit better. With the former it is doing extra work (i.e. double the number of loops).Here is the refactored code. It is annotated with the bugs and fixes:
In the above code, I've used
cppconditionals to denote old vs. new code: