-1

when I try the following code in visual studio it gives me 45 but when I run it in online compilers some give me an error and some give me 0.I was expecting that they all give me an error.how is that they are not?! thanks

#include <stdio.h>

int *f(int *a)
{
    *a = 23;
    int b = 45;
    return &b;
}

int main(void)
{
    int i = 2;
    int *p;
    p = f(&i);

    printf("The return value of function f: %d\n\n", *p);
    return 0;
}
MD XF
  • 7,860
  • 7
  • 40
  • 71
  • You are returning a reference to a stack allocated variable - this is **very** bad!! Don't do this, this can cause tons of nasty, hidden bugs – UnholySheep Oct 21 '16 at 17:50
  • 1
    Even if you are getting correct value in visual studio, this is wrong. You don't get any error since function's return type is int* and you are returning an int*. – MayurK Oct 21 '16 at 17:51
  • @MayurK Just because the re is *no* correct value.. – Eugene Sh. Oct 21 '16 at 17:52

1 Answers1

1

Problem:

return &b;

You are returning a pointer to a local variable that is going out of scope - hence the pointer will be invalid

If you get an error depends on the various settings for that compiler

Ed Heal
  • 59,252
  • 17
  • 87
  • 127