3 ms·
> One of the few reasons I ever even reached to C is the ability to slurp in data and reinterpret it as a struct, or the ability to reason in which registers th
by cbmuser 5y ago
> One of the few reasons I ever even reached to C is the ability to slurp in data and reinterpret it as a struct, or the ability to reason in which registers things will show up and mix in some `asm` with my C.
Which results in undefined behavior according to the C ISO standard.
Quote:
“2 All declarations that refer to the same object or function shall have compatible type; otherwise, the behavior is undefined.”
From: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf 6.2.7
- jstanley 5y agoExactly.
- innocenat 5y agoHow? I mean, doesn't GP mean this? struct whatever p; fread(p, sizeof(p), 1, fp);
- deleted 5y ago[deleted]
- tsimionescu 5y agoIt should be perfectly fine to do this: union reinterpret { char raw[100]; struct myStruct interpreted; } example; read(fd, &example.raw) struct myStruct dest = interpreted; This is standard-compliant C code, and it is a common way of reading IP addresses from packets, for example.
- saagarjha 5y ago(It should be noted that this is not valid C++ code.)
- jart 5y agoSensitive emotional subjects shouldn't be noted. Reminding C developers of the void* incompatibility is a good way to get them to feel triggered because it makes the language unpleasant.
- deleted 5y ago[deleted]
- jart 5y agoYou don't even need to pun that. It's legal to say: struct myStruct example; read(fd, &example, sizeof(example)); That "should present no problem unless binary data written by one implementation are read by another" quoth ANSI X3.159-1988. One example of a time where I've used that, is when storing intermediary build artifacts. Those artifacts only exist on the host machine. If the binary that writes/reads those artifacts gets recompiled, then the Makefile will invalidate the artifacts so they're regenerated. Since flags like -mstructure-size-boundary=n do exist and ABI breakages have happened with structs in the past.