0

Please find the code snippet shown below:

unsigned char au8Buffer[4] = {1, 2 , 3, 4} ;//Global array declared
class abc
{
    public:
    unsigned char *Getheader();
}
void func(abc *ptr)
{
    unsigned int a, b;
    a = (ptr->Getheader())[0];
    b = (ptr->Getheader())[1];
    printf("the value of A = %d\n",a);
    printf("the value of B = %d\n",b);
}
unsigned char * abc:: Getheader(void)
{
    static int count  = 0;
    count++;
    if(1 == count)
        return &au8Buffer[0];
    else
        return &au8Buffer[1];
}
main()
{
    abc Testobj;
    func(&Testobj);
}

Can someone please tell me why is the value of the variable 'b' coming as 3?. I was expecting the value of b to be 2.

Maddy
  • 503
  • 4
  • 12
  • 21
  • 1
    The code exhibits *undefined behavior* as the `GetHeader` function returns a pointer into an array whose life-time ends when the function returns (immediately making the pointer invalid). – Some programmer dude Aug 04 '20 at 11:00
  • 1
    Besides the undefined behavior, please learn some common debugging techniques, like [rubber duck debugging](https://en.wikipedia.org/wiki/Rubber_duck_debugging). And using pen-and-paper to draw out arrays and pointers. – Some programmer dude Aug 04 '20 at 11:01
  • 1
    Apart from UB, your `count` variable is declared `static`. Which means it preserves its value across function calls. So, since `Getheader()` is called twice, the value of `count` reaches 2 which triggers the "else" branch... – Igor G Aug 04 '20 at 11:11

1 Answers1

1

Every object and reference has a lifetime, which is a runtime property: for any object or reference, there is a point of execution of a program when its lifetime begins, and there is a moment when it ends. The lifetime of au8Buffer ends when the function ends. Returning a pointer to its contents results in undefined values. You can create a constructor for abc and move the initialization of au8Buffer into the constructor.

Kobby Owen
  • 85
  • 1
  • 8