Corry Chapman Corry Chapman - 2 months ago 15
C Question

Struct variable changes value with printf

I have a struct with an array of pointers to integers. The value of the first pointer is changing between calls to printf. This doesn't happen unless I generate the struct via a function. The code is below. Can someone tell me what's happening? Thanks.

struct a {

int *nums[10];

};

struct a *makeS();


int main(int argc, char *argv[]){

struct a *_b = (struct a*) malloc(sizeof(struct a));

struct a *_c = makeS();

int i = 1;

_b->nums[0] = &i;

printf("Num is %d\n", *_b->nums[0]); // prints 1
printf("Num is %d\n", *_b->nums[0]); // prints 1
printf("Num is %d\n", *_b->nums[0]); // prints 1
printf("Num is %d\n", *_b->nums[0]); // prints 1 … etc.


printf("Num is %d\n", *_c->nums[0]); // prints 1
printf("Num is %d\n", *_c->nums[0]); // prints 0
printf("Num is %d\n", *_c->nums[0]); // prints 0
printf("Num is %d\n", *_c->nums[0]); // prints 0 … etc.


}

struct a* makeS(){

struct a *_s = (struct a*) malloc(sizeof(struct a));

int i = 1;

_s->nums[0] = &i;

return _s;

}

Answer

Your problem is in the function:

  struct a* makeS(){

      struct a *_s = (struct a*) malloc(sizeof(struct a));

      int i = 1;

      _s->nums[0] = &i;

      return _s;

 }

int i goes out of scope as it is a local variable, meaning you are using a dangling pointer.

The memory used by i is free to be used by something else, and is most probably repurposed by the buffer or working space used in the subsequent printf calls.

Comments