2

I'm learning C and encountered a problem with structs.

Let's assume I have the following struct:

typedef struct {
  int x;
} Structure;

int main (void) {
  Structure *structs[2];
  for(int i = 0; i < 2; i++) {
    Structure s = {i};
    structs[i] = &s;
  }
  for(int i = 0; i < 2; i++) {
    printf("%d\n", structs[i]->x);
  }

  return 1;
}

The output is:

1
1

I don't understand why the new struct is overring the old one.

It might be a stupid problem. But I don't get it.

Thanks!

Solved:

typedef struct {
  int x;
} Structure;

int main (void) {
  Structure *structs[2];
  for(int i = 0; i < 2; i++) {
    Structure *s = (Structure *)malloc(sizeof(Structure));
    s->x = i;
    structs[i] = s;
  }
  for(int i = 0; i < 2; i++) {
    printf("%d\n", structs[i]->x);
    free(structs[i]);
  }

  return 1;
}

3 Answers 3

4

The object s doesn't live beyond the scope of the first for loop. Storing its address is pointless, and dereferencing it is undefined behaviour.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I got it! I changed my code to using the heap as storage.
3

Code has undefined behavior. You are holding the reference of a local automatic variable.

for(int i = 0; i < 2; i++) {
    Structure s = {i};
    structs[i] = &s;

} // life time of s ends here

All bets are off since code has UB. So, it doesn't matter what output you get.

5 Comments

It's not that the variable is local - if it was static, no UB would be here. The correct (complete) terminology is "local automatic" variable.
@H2CO3: Actually, it's "object with block scope and automatic storage duration". I don't believe the standard uses the term "local" for this -- or "variable" for that matter.
@KeithThompson Right, rather "block scope" - but I didn't imply "variable" was part of the terminology either (that's why it's ouside the quotation marks and the italics).
@H2CO3 Thanks for correcting me to use the correct terminology.
@Mahesh Thank Keith Thompson for that - it turned out that I wasn't entirely correct either :)
1

The Structs s = {i}; only has scope within the for loop where you declared it. Once you leave that loop, it no longer exists, even though you still have a pointer to it. It's all undefined behavior after that.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.