0

I am trying to modify a static struct object by passing its pointer to another function and modifying it by pointer inside that. But even after execution of modifying function, the values of the struct are intact.

void some_functon_a(....)
{
    static struct some_struct obj;
    modifier_function_b(&obj);
    // obj is not modified as expected in fact not at all
}

void modifier_function_b(struct some_struct *ptr)
{
    // modifying the struct using ptr 
}

Also when I run gdb on this code, I see as soon as code flow enters modifier_function_b() function gdb reports two entries for variable ptr: ptr and ptr@entry. All the modifications are being done on ptr, while ptr@entry which points to real location of obj is not modified. Can somebody point out what may be happening here? Are pointer to static variables kind of const pointers and we can't modify them outside their scope?

One more thing... this behavior is not seen if i remove static qualifier, which led me to think that pointer to static is kind of const pointer.

Thanks in advance :)

Naveen Rawat
  • 81
  • 2
  • 6
  • exactly what code is in modifier_function-b? Const'ness is lost after compilation is over, so there's no "no, don't let it change" going on. – xaxxon Aug 29 '13 at 06:55
  • I'm guessing your modification code is wrong, since I've just written something that corresponds to your description and it doesn't exhibit this problem. See my answer below. – xaxxon Aug 29 '13 at 07:06
  • Also, why are you expecting the pointers to change? – xaxxon Aug 29 '13 at 07:10
  • Wait, you're not trying to assign directly to ptr are you? Like ptr = malloc(...) or something. That would never be expected to work, since ptr in modifier_function_b is a local copy (remember, c is always pass by value) – xaxxon Aug 29 '13 at 07:12

1 Answers1

0

This program works as expected. It prints out 1 2 then 5 6. Also, you didn't specify language, but this does the expected in both C and C++

#include <stdio.h>

struct bar {
    int i;
    int j;
};

void b(struct bar * foo) {
    foo->i = 5;
    foo->j = 6;
}

void aa(){
    static struct bar a;
    a.i = 1;
    a.j=2;
    printf("%d %d\n", a.i, a.j);
    b(&a);
    printf("%d %d\n", a.i, a.j);
}


int main(){
    aa();

}
xaxxon
  • 19,189
  • 5
  • 50
  • 80
  • Thanks for the quick reply. This is of course not the actual code... this is just the part i thought relevant for the issue. Right now, if I run the code and do not use gdb debugging, I see that code is behaving as expected using printk statements, but when I try to step debug using gdb, it behaves as mentioned in original question. Does this means I should not always trust debuggers ? – Naveen Rawat Aug 29 '13 at 08:01
  • Yes... will that have any affect in this case ? – Naveen Rawat Aug 29 '13 at 17:52