2

In this piece of code i wanted to scan a word and return it backwards. I tried using different methods, but i dont seem to make it work.

This is what I am now left with.

#define WORD_LENGTH 256

char * stringBackwards(char *a) {

     char *palindrom = malloc(WORD_LENGTH * sizeof(char));
     int k = 0;
     for ( int i = WORD_LENGTH; i >= 0; i--, k++) {
          palindrom[k] = a[i];
     }

     return palindrom;
}

main() {
     char word[WORD_LENGTH];

     printf("Please enter a word \n");
     scanf_s("%s", word, WORD_LENGTH);

     printf("%s", stringBackwards(word));

     return 0;
}

It always returns me some strange symbols in my console.

I hope some of you can help me in correcting this.

Luna
  • 29
  • 3
  • you're swapping the whole buffer, not only the string. so you get the garbage which is in the end of `word` at the start of your reversed string. – Jean-François Fabre Nov 25 '17 at 20:59
  • I already though of that. But even if I set the WORD_LENGTH to 4 and enter 4 random letters I get garbage. – Luna Nov 25 '17 at 21:02
  • First of all you need to remember that `char` strings are really called ***null-terminated** character strings*. That null-terminator need to be handled. Then think of the case where the user inputs e.g. a two-character string? What will the rest of the 253 characters be initialized to? Hint: They *won't*. – Some programmer dude Nov 25 '17 at 21:03
  • yeah, because string isn't nul terminated: 2 issues – Jean-François Fabre Nov 25 '17 at 21:03
  • Perhaps you need to learn about the [`strlen`](http://en.cppreference.com/w/c/string/byte/strlen) function? Or get [a good beginners book or two](http://stackoverflow.com/questions/562303/the-definitive-c-book-guide-and-list) which will explain all this. And think about that when you use your function in the call to `printf`, who will call `free` for the memory you `malloc`? – Some programmer dude Nov 25 '17 at 21:04
  • Well this would obviously help alot. I am starting to learn C... dont be to rude please. But thank you anyway – Luna Nov 25 '17 at 21:06

1 Answers1

1

you're swapping the whole buffer, not only the string. so you get the garbage which is in the end of word at the start of your reversed string. The next mistake here is not terminating your string.

I would fix it like this (and rewrite your loop with increasing indexes, or it's very easy to make a 1-off mistake):

char * stringBackwards(const char *a) {

 int sz = strlen(a);
 char *palindrom = malloc(sz+1);  // size + 1 for nul-termination char
 int k;
 for ( k = 0; k < sz; k++) {
      palindrom[k] = a[sz-k-1];
 }
 palindrom[k] = '\0'; // don't forget to nul-terminate
 return palindrom;

}

aside: store the returned value to be able to free it if needed. Passing it to printf directly is a memory leak.

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219