Spot the Bug: Unmanaged Memory Traps
Join the DZone community and get the full member experience.
Join For Freesometimes i forgot how good life is in the managed lane. then i do some unmanaged work and get a good reality check.
let us look at the following structures:
[structlayout(layoutkind.explicit, pack = 1)] public struct pageheader { [fieldoffset(0)] public long marker; [fieldoffset(8)] public ushort lower; [fieldoffset(10)] public ushort upper; [fieldoffset(12)] public int overflowsize; [fieldoffset(16)] public int itemcount; } [structlayout(layoutkind.explicit, pack = 1)] public struct fileheader { [fieldoffset(0)] public long marker; [fieldoffset(8)] public logheader active; [fieldoffset(44)] public logheader backup; [fieldoffset(80)] public treerootheader root; [fieldoffset(142)] public treerootheader freespace; } [structlayout(layoutkind.explicit, pack = 1)] public struct treerootheader { [fieldoffset(0)] public long rootpagenumber; [fieldoffset(8)] public long branchpages; [fieldoffset(16)] public long leafpages; [fieldoffset(32)] public long overflowpages; [fieldoffset(40)] public long pagecount; [fieldoffset(48)] public long entriescount; [fieldoffset(56)] public int depth; [fieldoffset(60)] public treeflags flags; } [structlayout(layoutkind.explicit, pack = 1)] public struct logheader { [fieldoffset(0)] public long marker; [fieldoffset(8)] public long lastlog; [fieldoffset(16)] public long lastlogpage; [fieldoffset(24)] public int itemcount; [fieldoffset(28)] public long options; }
and now we have the following code:
private static unsafe void main() { intptr pageptr = marshal.allochglobal(4096); var pageheader = (pageheader*) pageptr.topointer(); pageheader->itemcount = 2; pageheader->marker = 0x128314543423; pageheader->overflowsize = 32; fileheader* fileheader = (fileheader*) pageheader + sizeof (pageheader); fileheader->root.branchpages = 0; marshal.freehglobal(pageptr); }
the fun part about this code is that it would silently corrupt the state of the process.
here is what happens when you run it under the debugger:
can you figure out why?
Published at DZone with permission of Oren Eini, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments