Re: Struct assignment




"Grey Alien" <grey@xxxxxxxxxxxxx> wrote in message news:erydna87m6gBFRvbRVnyjwA@xxxxxxxxx
If I have the ff struct:

struct A
{
unsigned int i;
char s[LONG_ENOUGH];
} a, b;


And use them in code like this:

a.i = 42 ;
strcpy(a.s,"test");

b.i = 100 ;

b = a ;

at this point, a (bitwise?) copy of a is made to b. Question is:

1). is b.s now ptr to a.s ? (I think so)
If so, what happens if for instance variable 'a' goes out of scope (?)

2). Does the compiler generate an implicit "memcpy" or "memmove" behind the scenes when it sees an assignment like this (to avoid dangling ptrs)?

The answer is 2. A structure assignment will cause a call to memcpy to be made, or equivalent code emitted if the structure is small enough to make this wasteful and the compiler is clever.
However if structures contain pointers then the values of the pointers are overwritten. So you have to be extremely careful not to orphan memory or create peculiar bugs with aliases.

--
Free games and programming goodies.
http://www.personal.leeds.ac.uk/~bgy1mm



.



Relevant Pages

  • Re: How to retrieve data from array of pointers or from a struct?
    ... This defines an array of pointers to unsigned long longs... ... of your compiler, I'm sure it would have told you. ... examples/zzzmain.c:295: undefined reference to `memcpy' ... #include only adds the necessary declaration, you still need to link the ...
    (comp.lang.c)
  • Re: restrict
    ... >> indeed defines memcpy() as taking two restrict pointers. ... > and the ISO C standard is unintentional. ... It makes it easier if the compiler writer wants to make the compiler ...
    (comp.lang.c)
  • Re: How to retrieve data from array of pointers or from a struct?
    ... You're declaring an array of pointers to unsigned long long, ... you're initializing the pointers with integer values. ... and your compiler should have warned ... You're not explicitly calling memcpy, ...
    (comp.lang.c)
  • Re: new IL: C (sort of...).
    ... only for "recent" Pascals, ... far pointers weren't really limited, ... in my compiler, I made wchar_t a builtin type (in most cases, aliased to ... I could very well include builtin "managed strings" in the new IL. ...
    (comp.lang.misc)
  • Re: new IL: C (sort of...).
    ... and the frontend compiler needs to be able ... Having very limited pointers is a fact of life in a VM language though, ... vague claims about Pascal's pointer support. ... That is pretty normal for standards (the ...
    (comp.lang.misc)