0

I saw some weird behavior with my C++ function whose work is to simply put 'n' ones(1).

char *getSpaces(int n) {

    char s[50];
    int i = 0;

    for(i=0; i<n; i++) {
        s[i] = '1';
    }

    s[i] = 0;
    return s;
}

When I do fout<< getSpaces(20), I get following output in the file :-

1111111111SOME_WEIRD_CHARACTERS_HERE

Can anybody explain this?

P.S. I am using codeblocks IDE on windows platform.

alk
  • 69,737
  • 10
  • 105
  • 255
DexterMorgan
  • 250
  • 2
  • 13
  • 3
    You're returning the address of a local variable. That ceases to exist when the function returns. Let me look for a duplicate. – Daniel Fischer May 25 '13 at 18:11
  • 1
    Also, `getSpaces(100)`. – mwerschy May 25 '13 at 18:13
  • Thanks for the answer! One more thing which I noticed is that when I tried allocating memory dynamically of size n(using new operator) within the function, it worked fine. Is it because I didn't delete dynamically allocated memory before exiting function? – DexterMorgan May 25 '13 at 19:26

0 Answers0