c - Why can I still access a member of a struct after the pointer to it is freed? -
if define structure...
struct linknode { int node_val; struct linknode *next_node; };
and create pointer it...
struct linknode *mynode = malloc(sizeof(struct linknode));
...and free() it...
free(mynode);
...i can still access 'next_node' member of structure.
mynode->next_node
my question this: which piece of underlying mechanics keeps track of fact block of memory supposed represent struct linknode? i'm newbie c, , expected after used free() on pointer linknode, no longer able access members of struct. expected sort of 'no longer available' warning.
i love know more how underlying process works.
the compiled program no longer has knowledge struct linkednode
or field named next_node
, or that. names gone compiled program. compiled program operates in terms of numerical values, can play roles of memory addresses, offsets, indices , on.
in example, when read mynode->next_node
in source code of program, compiled machine code reads 4-byte numerical value reserved memory location (known variable mynode
in source code), adds 4 (which offset of next_node
field) , reads 4-byte value @ resultant address (which mynode->next_node
). code, can see, operates in terms of integer values - addresses, sizes , offsets. not care names, linkednode
or next_node
. not care whether memory allocated and/or freed. not care whether of these accesses legal or not.
(the constant 4 repeatedly use in above example specific 32-bit platforms. on 64-bit platforms replaced 8 in (or all) instances.)
if attempt made read memory has been freed, these accesses might crash program. or might not. matter of pure luck. far language concerned, behavior undefined.
Comments
Post a Comment