3 ms·
The article kind of lost me at the first example. struct{ char x char y; }a; memset(&a, 0, sizeof(char) * 2); What does the compiler know about
by scoutt 7y ago
The article kind of lost me at the first example.
struct{
char x
char y;
}a;
memset(&a, 0, sizeof(char) * 2);
What does the compiler know about memset? Why it should? It can be a function called heyLetsFillTheMemoryOverHere(&a, wrongSize); and still it's the programmer's fault.
In fact, it's a good thing that C doesn't care about memset, and doesn't get in between me and my code. And that's I love about C. It minds its own business and does what I tell it to do.
> If I use my compiler to compile a program on my machine, the compiler knows that I’m compiling it to the x64 instruction set
You can be cross-compiling. I do it every day. The C language doesn't need to know about every little platform out there. If a compiler wants to go the extra mile and help about it, that's a compiler-thing and not a C-language-thing.
If there is a MCU that uses 3 bytes words, why should C be aware of it, 40 years before?
Don't blame the specifications, blame the compiler if you want.
Edit: removed a couple of personal opinions.
- saagarjha 7y ago> What does the compiler know about memset? Why it should? It can be a function called heyLetsFillTheMemoryOverHere(&a, wrongSize); and still it's the programmer's fault. Because memset is defined by the ISO C standard to have specific semantics, which the compiler can leverage to make your code faster.
- scoutt 7y ago> void memset(void s, int c, size_t n); > The memset() function shall copy c (converted to an unsigned char) into each of the first n bytes of the object pointed to by s. The standard just declares an interface, to be added to a C library (maybe?). It's not the job of the compiler to check for programmer's faults. The compiler doesn't care and it shouldn't.
- deleted 7y ago[deleted]
- gpderetta 7y agoThe standard defines the behaviour, not just the signature. Memset has been treated as a builtin since forever.
- MaxBarraclough 7y agoCertain standard-library functions actually do seem to get special treatment by the C standard. memcpy and memmove get special treatment regarding effective type. I don't think there's any such special treatment for memset. https://en.cppreference.com/w/c/language/object#Effective_type https://en.cppreference.com/w/c/language/object#Effective_ty... > Don't blame the specifications, blame the compiler if you want. We're not talking about bugs in compilers (in which case you can blame the compiler), we're talking about standards-compliant compilers (in which case you blame the standard).