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

2
  • 1
    @dbeer Don't do that. The homework tag is deprecated. Commented Nov 28, 2012 at 21:54
  • Sorry, I somehow missed that. Commented Nov 28, 2012 at 21:54

1 Answer 1

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];
Sign up to request clarification or add additional context in comments.

4 Comments

or perhaps dest and scr point to the same address as compilers may optimise assignment to identical string literals to conserve memory (see stackoverflow.com/questions/11399682/…)
@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 = "";.
@Carbonic thanks for the explanation - so char dest[]="" is not a string literal with static storage, its a local array?
have just found this which explained things [stackoverflow.com/questions/2036096/… - bit of a C gotcha if you don't know whats going on...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.