Q:

C Unexpected string returned from function behaviour

I am quite new to C and I am playing with some string operations. I have encountered quite a strange problem for me while returning a string from a function. My simple program is as follows:
int main(int argc, char* argv[])
{
    char text[] = "abAB";

    char* out = testString(text);

    printf("Result Text: %s", out);
    printf("\n");
}

char* testString(char* input) {
    char* text = copyString(input);

    return text;
}

The copyString function defines a simple operation to copy one string to another. It is as follows:
char* copyString(char* input) {
    char output[100];

    int index = 0;
    while (input[index] != '\0') {
        output[index] = input[index];
        index++;
    }

    output[index] = '\0';

    return output;
}

The problem is that while I am debugging the application, the string I am returning from a function seems to be OK (Visual Studio visualises it well enough) and when the printf line occurs, the string outputted on the stdout is something completely strange and unfamiliar - a smily face. Sadly, I can't post images yet in order to show you what I see in my console as output.
I am using Visual C++ Express 2010 as an IDE if this could be helpful.

A:

You are returning a variable declared within a function, which will cease to exist outside the scope in which it is declared. Use a dynamically allocated char array and then return a pointer to it.
char* output = malloc(100 * sizeof(char));
...
return output ;

Note : You are assuming that input string is less than 100 characters. Instead of that, try passing the length of string as a parameter or use strlen. Your program will crash if input string has more than 99 characters.
Also as noted in comments, free the memory allocated when you are done using it.

