I assume you wanted your code to look like this:
void *memset(void *_p, unsigned v, unsigned count) {
unsigned char *p = _p;
- while(count-- > 0) *p++ = 0;
+ while(count-- > 0) *p++ = v;
return _p;
}
In which case, I'm not sure what you're complaining about. Is it that memset here has a non-standard signature (v is supposed to be int, not unsigned)? Or that the "before" code ignored v? Or the un-braced loop body on the same line? Or is the some other problem I'm overlooking (which is possible, it's been about a decade since C was my main day-to-day language)?[Edited to try to coax better text formatting from HN]
Oh I know, the writer obviously wants very very badly to write this while loop as a one-liner. That's the start of all the other badness. As a reader of this code now, I have to keep every possible combination of post-increment side effects and precedence rules in mind before this code makes sense.
And yes, I know code like this is quoted in books as example of how cleverly you can write "powerful" one-liners. As far as I'm concerned, it's just a dumb show of alpha-coder pride and it's not a surprise to me that a serious bug was buried here.
Finally, the same people who write that kind of code also write things like f(x++, (x+1)) without realizing that this is undefined in C.
Also, as an added bonus, postincrement/decrement sometimes creates extra unwanted copies in C++ so you need to use the pre- versions.
Compilers are good enough to handle tight loops like this even on very low optimization settings. Better to write that stuff out.
I have found that as I program more, I kind of agree with Crockford that ++, and -- are evil and should always be replaced by pp += 1; What that does is force you to avoid actions in conditional expressions and pull the mutators inside the block. It also forces you to be explicit about when you expect the increments to happen.
Those are fundamental things that should be second-nature to you if you claim to really know C, just as a mathematician would know that exponentiation has higher precedence than multiplication which has higher precedence than addition.
> Did p get incremented or did p get incremented?
There's an easy and concise mnemonic for the precedence of ++/-- and dereference - just remember that this is a strcpy, as shown in K&R:
while(*dst++ = *src++)
;
So here it is the pointer that is incremented, and not what it points to.> Finally, the same people who write that kind of code also write things like f(x++, (x+1)) without realizing that this is undefined in C.
Those are the people who think they know C, but actually don't; it's an issue of not knowing what you don't know, and in such situations you should either seek to find the answer, or be conservative.
That's a bogus argument. There's an easy way to write code that's readable and maintainable by mixed teams and then there's this macho way of showing off to no particular advantage.
- just remember that this is a strcpy, as shown in K&R: while(dst++ = src++) ;
Or -- just don't. Just write code that doesn't rely on every reader to mentally clear through a dense thicket of precedence and side-effects to understand your strcpy and get your job done in a pragmatic fashion with 4 lines of easily understood C code instead of 1 line that makes your heart glow with momentary pride.
*s = 0;
s++;One could reasonable speculate if a code-reviewer had sent the original code back to be written in a readable fashion, the actual bug in the code would have been caught too.
I can see your point about *p++ being a speed bump, but overall this version seems less complex to me.
Given the kinds of projects I've been part of are already swarming with (externally imposed) system complexity to begin with, an attitude of "I write dense code since I'm a professional" won't get anyone very far in such teams.
And yet we started off discussing a serious bug in libc discovered in exactly that kind of code. That's the libc in Android!! My argument is that the extra cognitive overhead of digesting needless complexity leads to the original authors and reviewers of the code to miss other obvious bugs.
I'm astonished at the vitriol
I'm sorry if my straightforward and respectful response to your dismissive and patronizing remarks sounds vitriolic to you.
This bug is simply a failure to test. Where was the trivial automated unit test for this library routine? Never written I imagine.
Reminds me of another buggy library I had to work with - the Linux c runtime. I was porting to a risc processor oh ten years ago. Something was wrong with the memcpy routine. So I wrote a unit test. A very thorough unit test. Found 12(!) bugs before I was through.
Test was: copy from aligned source + (0..128) to aligned destination + (0..128) length (0..128). Simple triple loop. Anybody could have written it. Nobody ever had.
This is not a C problem, or an Android problem. Its an industry problem. Intel shipped a Pentium processor once upon a time that couldn't divide by 10.
Would we criticize assembler because its full of confusing registers and stuff? Sure go ahead; but it sounds silly.
NEVER WRITE THIS CODE! EVER!
This is the code that gives us the classic buffer overflow vulnerability all because checking for a length isn't elegant.
Also, how does this code work if what one of those pointers points to are declared volatile? What if both pointers point to volatile things? What happens if one of those pointers crosses through 0 because it rolled over from max?
Thanks. I doubt you could have provided a better example of the precise problem.
The few characters it would take to check length didn't effect this API, it was just part of the decision to use null terminated strings instead of storing lengths.
>Also, how does this code work if what one of those pointers points to are declared volatile? What if both pointers point to volatile things?
I can't imagine any way in which volatile would cause problems. What are you pondering? strcpy doesn't take volatile pointers anyway.
> What happens if one of those pointers crosses through 0 because it rolled over from max?
That's just a very specific type of buffer overflow. strcpy is the wrong function to use in such a scenario.
> Thanks. I doubt you could have provided a better example of the precise problem.
strcpy is for very specific situations. Writing it in a simple way isn't the problem. It's not like it's even theoretically possible for strpy to avoid overflowing. It doesn't have enough information, only two pointers.
In short, this is a bad API, it is not a bad implementation.
Termination condition. Which data applies and does it have to be reread after the assignment?
Note that this "elaborated" version,
while(*src) {
char c = *src;
src++;
*dst = c;
dst++;
}
if the pointers were volatile, would actually read the source value twice. char c;
do {
c = *src;
src++;
*dst = c;
dst++;
} while (c != '\0');
But, even here, people reading the code can reason about the volatiles without having to go look up the standard.And don't even get me started about compiler implementation of volatile.
No coding style is immune to problems caused by changing the number of reads to a variable. Volatile is an exceptional thing that must be treated with care and heavy documentation. It has no relevance to the quality of a normal-code strcpy.
Or rather, buffer overflows arise because someone did not think of lengths, and somehow this mentality became ingrained in a rather large number of programmers; this code is perfectly fine if the length of the source string is always less than or equal to that of the destination. I think saying "never use X" is almost always a bad idea, since it discourages reasoning, and not thinking about lengths is what lead to this problem in the first place.
On the other hand, "never use gets()" is more appropriate, since whoever came up with that function clearly never thought of lengths...
Questions like this and others (eg., does the pointer deref operation applies to incremented or non-incremented value of p?) that you have to answer before you can make sense of the code. The cognitive overload on the reader's brain is at least part of the reason that a bug like that went past code-review in memset function on a major platform. MEMSET !! Was the needless cleverness and terseness of the code worth it?
P.S. The answer to your question is No. The variable count as used in the body of this function is local to this function (it's passed by value... so it's a copy of what the caller passed).
You have an interesting take on C.
And I don't see what's 'clever' about decrementing a count instead of incrementing a count.
It would be just as easy to assign 0 in a larger function, and I see no way of reducing the cognitive load. This line isn't doing anything complex or weird.
Can't tell if this question is referring to something I said? If so, I'd like to know what I said that implied such a thing.
The only way to avoid altering the count parameter is to make a new variable for counting.
The single line while loop there is just bristling with pitfalls. I'd reject such code in code review and ask it to be rewritten in more readable C. As an added bonus, this exercise would probably also have caught the original bug that started this discussion.
The pass-by-value question came from someone who hadn't written C code in years and I'm pretty sure a practicing C coder (in production code) would not have that question in the first place. Or if it does come from a fresh programmer just getting started, it'll only take one code review to get that straight (and probably earn that programme's work some added scrutiny for some time).
C++ added pass by reference (&), which can be a handy bit of syntactic sugar.
What you're saying is correct in the practical sense. But ggreer's answer is the real technically detailed explanation (everything is passed by value, including pointers to memory. But then you can manipulate that memory you have the pointer to. And that makes it effectively pass-by-reference). Also, C++ adds a language defined pass-by-reference operation... so there's that.
[Now I wait for a deluge or replies about how it's "idiomatic" C. All I have to say to that is, s/ma// ]
[Edited later to use the code mode]