0

I am getting some strange behavior from VS. I printf using the same line of code in MAIN() and get difference answers?

void aligator(int **p) {
  int pet[6] = { 10, 20, 30, 40, 50, 60 };

  *p = pet;

  printf("pet[2]:%d\n", pet[2]);
  printf("p[2]:%d\n", *((*p) + 2));
}


int main()
{
  int *pa;

  aligator(&pa);

  printf("_pa[2]:%d\n", *(pa + 2));
  printf("_pa[2]:%d\n", *(pa + 2));
  printf("_pa[2]:%d\n", *(pa + 2));
  printf("_pa[2]:%d\n", *(pa + 2));
}

RUN THE PROGRAM:

pet[2]:30
p[2]:30
*pa[2]:30   //
*pa[2]:0    // why?
*pa[2]:0    //
*pa[2]:0    //
Dmitry Sazonov
  • 8,801
  • 1
  • 35
  • 61
jdl
  • 6,151
  • 19
  • 83
  • 132
  • 5
    It is UB - you are storing external pointer to a local variable `pet[6]`. – Dmitry Sazonov Jan 25 '18 at 14:05
  • 2
    After `aligator` returns, `pa` points to an array that no longer exists. Using it is then undefined behavior. – François Andrieux Jan 25 '18 at 14:05
  • Its's C++: `std::vector aligator() { return { 10, 20, 30, 40, 50, 60 }; } ` –  Jan 25 '18 at 14:10
  • 3
    In particular, immediately after `aligator()` returns, the (invalid) memory `pa` points to may still contain `30` at index 2 long-enough for the first `printf()` call to print it, but in doing so, it will have overwritten the stack so subsequent calls see different values. – TripeHound Jan 25 '18 at 14:17

0 Answers0