4 ms·
I'm fairly new to C, am I understanding correctly that the new syntax is just sugar for a struct containing two values: a pointer to the start of the array, and
by andai 5y ago
I'm fairly new to C, am I understanding correctly that the new syntax is just sugar for a struct containing two values: a pointer to the start of the array, and its length? This can of course be done without the new syntax, and it seems exceedingly useful. Are such structs commonly used in C projects?
What is the actual source of bugs in this regard? How does passing the length as a separate parameter lead to more bugs than having it bundled -- is the main source of error passing the wrong variable?
- thingsgoup 5y agoIf the length is bundled with the pointer as syntax then the compiler and maybe even the runtime can provide checking on behalf of the programmer. Passing it by hand means it’s the programmers responsibility to (remember to) validate
- WalterBright 5y ago> How does passing the length as a separate parameter lead to more bugs than having it bundled It boils down to being inconvenient, unreliable, error prone, and difficult to audit. That's why it isn't used and C's #1 problem remains buffer overflows. And so it goes for all the other solutions for C for this problem, except my proposal. My proposal is how D works, and it's been convenient, reliable, robust and auditable for 20 years. You can still use raw pointers in D, they are fully supported, but the use of the arrays make use of raw pointers rare.
- coldtea 5y ago>This can of course be done without the new syntax, and it seems exceedingly useful. Are such structs commonly used in C projects? There are string libraries that work that way in C. If you do it manually, without a lib, then you need to check that the length is valid yourself (after every operation), so it's not as useful as a language with first class support for it.
- naasking 5y agoPresumably you can add an inlined array access function or macro in the header to do this for you.
- WalterBright 5y agoIf that worked, people would have done it, and C buffer overflows would be a thing of the past.
- naasking 5y agoThe reason this hasn't been done is mostly because C programmers have an allergy to runtime checks that might slow their programs by even single digit percentages.
- WalterBright 5y agoPeople don't use these other schemes because they are clumsy, inconvenient, look bad, and have never caught on. With it as part of the syntax, it becomes natural to use them. I'm not making this up, it is based on extensive experience. The runtime overflow checks can be turned on and off with a compiler switch, so it becomes trivial to see what performance effect it actually has. Critical loops can be coded with ordinary pointers as necessary. For the rest, the performance effect is not measurable. Again, this is from experience, not supposition.