0

I have this problem with an assignment. Im supposed to reverse a string recursively into another empty string. The thing is that the function modifies the source string which it is not supposed to do, just to copy the string backwards to the destination string. I don't understand why this is happening...

#include <stdio.h>
#include <string.h>

void
invert(const char *src, char dest[])
{
    if(*src=='\0')
        return;
    else
    {
        invert(src+1, dest);
        dest[strlen(src)-1]=*src;
    }
}

int main(int argc, const char * argv[])
{
    char dest[]="";
    char src[]="";
    printf("write a word: \n");
    scanf("%s", src);
    invert(src, dest);
    dest[strlen(src)]='\0';
    printf("the inversion of the word is: %s\n", dest);
    return 0;
}

For example: writing Ulysses => sessesU and writing Jones => seesJ\377

patriques
  • 5,057
  • 8
  • 38
  • 48
  • 1
    @dbeer **Don't do that.** The `homework` tag is [deprecated](http://meta.stackexchange.com/questions/147100/the-homework-tag-is-now-officially-deprecated). –  Nov 28 '12 at 21:54
  • Sorry, I somehow missed that. – dbeer Nov 28 '12 at 21:54

1 Answers1

4

The problem is here:

char dest[]="";
char src[]="";

you're allocating two times one character - the variables are probably next to each other on the stack, that's why writing to the one erroneously overwrites the contents of another.

You should allocate sufficient storage for the strings. If you're sure the input of your program will never exceed for example 1023 bytes, then two 1k buffers should be good:

char src[1024], dest[1024];
dreamcrash
  • 47,137
  • 25
  • 94
  • 117
  • or perhaps dest and scr point to the same address as compilers may optimise assignment to identical string literals to conserve memory (see http://stackoverflow.com/questions/11399682/c-optimisation-of-string-literals) – bph Nov 29 '12 at 00:10
  • @Hiett In no way. Since `dest` and `src` are declared as arrays, and not pointers, they're stack-allocated and pre-filled with the appropriate string. Your statement would be true if the declaration was `const char *src = "", *dest = "";`. –  Nov 29 '12 at 05:43
  • @Carbonic thanks for the explanation - so char dest[]="" is not a string literal with static storage, its a local array? – bph Nov 29 '12 at 09:29
  • have just found this which explained things [http://stackoverflow.com/questions/2036096/literal-string-initializer-for-a-character-array] - bit of a C gotcha if you don't know whats going on... – bph Nov 29 '12 at 12:24