c - Underallocating memory for a union -


given declaration:

struct s1 {     int type;     union u1 {         char c;         int i[10000];     } u; } s; 

i'm wondering whether can allocate less memory struct sizeof(struct s1) suggest:

struct s1 * s_char = malloc(sizeof(int)+sizeof(char));  

on 1 hand, seems intuitive: if 1 knows s/he never reach past char s_char.u.c, allocating whole sizeof(struct s1) looks big waste.

on other hand, rather understand c11 standard against - it's never spelled out. 2 passages have found can understood being against these:

  • if struct somehow assumes full size has been allocated, opens door undefined behavior: new object can allocated after s_char still inside of "real" sizeof(struct s1) bytes assumed struct, trigger item 54 of annex j.2 of c11 standard: ub if

an object assigned inexactly overlapping object or overlapping object incompatible type (6.5.16.1).

  • 6.2.6.1 paragraph 7:

when value stored in member of object of union type, bytes of object representation not correspond member correspond other members take unspecified values.

but can understood either standard refusing deal happens values, or saying values can expected change arbitrarily.

in summary, there intuition of "but we're using 5 bytes!" vs language-lawyeristic caution - not proof. , question is: there more evidence side? more concretely: ever ok underallocate memory union or other data structure?

again: intuition brought problem, don't want more of it. looking reasoned on reliable facts, c11 standard and/or compiler information. also, know standard way substitute struct-with-union union-of-structs common initial sequence, though not without risks... . tangential here.

you seem confusing looking answer that's outside scope of c language. @m.m says, issue isn't specific unions. if don't allocate sufficient memory object, , write part of object outside allocated memory, don't surprised if things go pear shaped later.

the c language lets define pointer known type, incomplete types "known" property name. it's programmer, when assign value pointer, ensure provided value valid. c treat pointed-to area object of pointer's type. that's convenience you, navigate memory.

keep in mind "where memory comes from" outside scope of language. come malloc, come sbrk(2) or mmap(2). or constant, video ram buffer in original ibm pc. if misdescribe thing pointed to, can't expect compiler come rescue.


Comments

Popular posts from this blog

php - How to display all orders for a single product showing the most recent first? Woocommerce -

asp.net - How to correctly use QUERY_STRING in ISAPI rewrite? -

angularjs - How restrict admin panel using in backend laravel and admin panel on angular? -