0
votes

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

1
@dbeer Don't do that. The homework tag is deprecated. - user529758
Sorry, I somehow missed that. - dbeer

1 Answers

4
votes

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];