Print a string reversed in C

c, reverse, string

Solution

You forget to terminate your string with `\0` character. In reversing the string `\0` becomes your first character of reversed string. First allocate memory for one more character than you allocated

char *res = malloc( longitud * sizeof(char) + 1);  

And the try this

for (i = 0; i < longitud-1; i++)
{
    res[i] = word[longitud - 2 - i];
}
res[i] = '\0'; // Terminating string with '\0'

Problem

I'm coding a program that takes some files as parameters and prints all lines reversed. The problem is that I get unexpected results: If I apply it to a file containing the following lines ``` one two three four ``` I get the expected result, but if the file contains ``` september november december ``` It returns ``` rebmetpes rebmevons rebmeceds ``` And I don't understand why it adds a "s" at the end Here is my code ``` #include <stdio.h> #include <string.h> #include <stdlib.h> void reverse(char *word); int main(int argc, char *argv[], char*envp[]) { /* No arguments */ if (argc == 1) { return (0); } FILE *fp; int i; for (i = 1; i < argc; i++) { fp = fopen(argv[i],"r"); // read mode if( fp == NULL ) { fprintf(stderr, "Error, no file"); } else { char line [2048]; /*read line and reverse it. the function reverse it prints it*/ while ( fgets(line, sizeof line, fp) != NULL ) reverse(line); } fclose(fp); } return (0); } void reverse(char *word) { char *aux; aux = word; /* Store the length of the word passed as parameter */ int longitud; longitud = (int) strlen(aux); /* Allocate memory enough ??? */ char *res = malloc( longitud * sizeof(char) ); int i; /in this loop i copy the string reversed into a new one for (i = 0; i < longitud-1; i++) { res[i] = word[longitud - 2 - i]; } fprintf(stdout, "%s\n", res); free(res); } ``` (NOTE: some code has been deleted for clarity but it should compile)

Original source