0

When I run the below program using Code::Blocks, the output is

1 2 3
8129912 -1 3

When I try it using ideone, I get an unspecified runtime error.

I would expect it to print

1 2 3
1 2 3

Can somebody explain why the string parameter makes a difference?

int* foo() {
    int a[3] {1, 2, 3};
    return a;
}

int* bar(string x) {
    int a[3] {1, 2, 3};
    return a;
}

int main() {
    int *p = foo();
    cout << p[0] << " " << p[1] << " " << p[2] << endl;

    int *q = bar("X");
    cout << q[0] << " " << q[1] << " " << q[2] << endl;

    return 0;
}
cpp beginner
  • 512
  • 6
  • 23
  • 1
    your array `a` lives on the stack and once you leave the scope of the function accessing this memory is undefined, you are just lucky that it works with the first because there was nothing else on the stack, while the parameter x goes on the stack – 463035818_is_not_an_ai Apr 25 '16 at 20:56
  • No one can usefully explain undefined behavior. It's undefined. In particular, each of your functions returns a pointer to data that were allocated on the stack, and whose lifetime ended when the function returned. Dereferencing (both of) those pointers produces undefined behavior. – John Bollinger Apr 25 '16 at 20:57
  • _"Can somebody explain why the string parameter makes a difference?"_ That's only secondary. Undefined behavior is appearing in first place because you're returning the address of a value that was allocated locally on the stack. – πάντα ῥεῖ Apr 25 '16 at 20:57
  • if you want to avoid such problems when passing/returning arrays from functions use `std::vector` instead, anyway you want to write c++, not c, no? – 463035818_is_not_an_ai Apr 25 '16 at 20:58
  • Ok, thanks for your comments. I'll read the duplicate answers carefully. – cpp beginner Apr 25 '16 at 20:59

0 Answers0