7

Just found this in a C lib:

struct Model
{
char* name;
};

struct ModelA
{
char* name;
int value;
...
};

ModelA* ma=...
...
Model* m=(Model*)ma; //!!?

is it legal?

Comments
  • 2
    It should work, probably - the memory layout of Model and ModelA (up to the first 4 or 8 bytes (the size of a pointer)) should be the same. A good idea? probably not.
  • 0
    @Lahsen2016 it's a example, actually it has more members.
  • 1
    Well, there shouldn't be any problem
    Unless you try to use "value" before re-initialization
    And it could give bigger problems if ma was an array since ma is a pointer and so is m. ma+1 has a size and m a different one which means overwriting stuff over and over
    It really isn't the best idea unless you really know what you're doing
    I wouldn't feel comfortable with a bomb like that
  • 1
    "legal" is very loosely defined in C. This technique is basically a poor man's interface. The important thing is that the members have to be in the same order and the same types.
  • 2
    That's legalish (hey, I guess it works), but I think that falls into the category of "Don't ever do this in production." I'm not positive if that falls into the category of undefined behavior, but I wouldn't be shocked if cranking the optimizations up on the compiler broke that
  • 0
    I just realized I didn't answer your question @cpp0xc0ffeeee
    It's perfectly legal, meaning it compiles correctly
    It won't work unless it's handled veery carefully
    And it's also unlikely to crash, meaning it will probably disrupt a shit ton of data before being corrected
    Avoid or refactor it, that's what I'd do
  • 1
    @Lahsen2016 do you explicitly search for "pointer" rants xD
Add Comment