0
#include <stdio.h>
#include <string.h>
char *reverse(char *input) {
                size_t  len = strlen(input);
                char output[len];
                output[len] = '\0';
               for (size_t  i = 0; i < len; i++) {
                  output[len - i - 1] = input[i];
               }
               input = output;
               return input;
       }

int main(){
    char string1[] = "Hi world, how are you doing, something";
    printf("\n");// output differs by commenting this line
    printf("%s\n",reverse(string1));
}

The result is wierd. Can anyone explain me why this happens? with the line 16, when it is commented, the output is something garbage value, whereas when a print statment exists before that, expected result is shown

without extra print statement enter image description here

with extra print statement enter image description here

Output when printf("\n"); is commented:

user1@h3:~/code$ ./x1
&&Ќ`we&
user1@h3:~/code$

Output when printf("\n"); is uncommented:

user1@h3:~/code$ gcc x1.c -o x1
user1@h3:~/code$ ./x1

gnihtemos ,gniod uoy era woh ,dlrow iH
  • 3
    You returned a pointer to a local value (`char output[len];`). – Ry- Oct 26 '22 at 20:16
  • 1
    Please post code, errors, sample data or textual output here as plain-text, not as images that can be hard to read, can’t be copy-pasted to help test code or use in answers, and are barrier to those who depend on screen readers or translation tools. You can edit your question to add the code in the body of your question. For easy formatting use the `{}` button to mark blocks of code, or indent with four spaces for the same effect. The contents of a **screenshot can’t be searched, run as code, or easily copied and edited to create a solution.** – tadman Oct 26 '22 at 20:17
  • 1
    ⟼Remember, it's always important, *especially* when learning and asking questions on Stack Overflow, to keep your code as organized as possible. [Consistent indentation](https://en.wikipedia.org/wiki/Indentation_style) helps communicate structure and, importantly, intent, which helps us navigate quickly to the root of the problem without spending a lot of time trying to decode what's going on. – tadman Oct 26 '22 at 20:17
  • Unfortunately, `output[len]` is outside the bounds of the array. Suppose `len` is 1. That means that `output` has one entry, `output[0]`, and that means that accessing `output[1]` is out of bounds. So accessing `output[len]` will always be out of bounds. – David Schwartz Oct 27 '22 at 19:59

0 Answers0