Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Question on Unions in C

Name: Anonymous 2012-06-24 2:12

So, I know that a pointer is a variable that stores a memory address (basic 4 or 8 bytes). If I place a pointer in a Union type, does the memory address stored by the pointer share the same memory space as the other types, or does the data at the memory address share the same memory?

Or, in other words, if I union a double and a char*, will I memory leak/segfault if I assign the double to anything?

Name: Anonymous 2012-06-24 15:46

So from what I'm getting in this thread... don't shove pointers in unions, that'll just cause an immediate segfault the second you change anything else. Now I question why the following is done in the Ruby interpreter:

#define RSTRING_EMBED_LEN_MAX ((int)((sizeof(VALUE)*3)/sizeof(char)-1))
struct RString {
    struct RBasic basic;
    union {
        struct {
            long len;
            char *ptr;
            union {
                long capa;
                VALUE shared;
            } aux;
        } heap;
        char ary[RSTRING_EMBED_LEN_MAX + 1];
    } as;
};

ary shares the same space as len, ptr, and aux, and VALUE is a void pointer. Should this not be considered dangerous practice that could easily run into a segfault the second ary is changed and ptr is accessed, or capa is changed and shared is accessed?

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List