121 points · by Garbage · 15y ago · 85 comments
Not to mention the wrapper can be inlined in C99, or would be automatically inlined with -O3 in gcc, not that it matters one iota in this case.
The other glaring bug would seem to be Windows' implementation for POSIX tmpfile() requiring admin access. But I guess that's not too surprising.
Frankly, I wish this sort of blog post wouldn't be upvoted here. It's one thing when someone asks a basic question on StackOverflow. Even experienced programmers can learn with the answers. But when someone writes an "authoritative" blog post that misses the basics, it's more noise than signal.
I agree about this being an insane premature optimization, but the C:\ being a bug regarding line continuation within comments? That's fucking fascinating.
I don't know - that's actually very surprising to me considering each user has their own temporary folder.
I can't imagine what reason could exist for this functionality except possibly to provide backwards compatibility with some popular apps that have been poorly written.
To extrapolate, I found it unsurprising not because it's either Windows or POSIX individually, but because it's both together.
It's been many years since I was a Windows developer, but I remember back then that the opinion of the POSIX implementation (XP era, not NT era) was "there be dragons" and to avoid it.
So, to get back to your question, the posix compatibility layer in Windows is very old and back then all the above didn't exist and they had to make a choice on how to implement the function. Back then (this decision may have been made as early as the late 1980's), using C:\ wasn't all that stupid an idea; either way, the point was that the file would be deleted when the file handle was closed anyway, so it's not like C:\ would be polluted with all sorts of files.
Of course those assumptions changed in the past 20 years, but you can't just change the behavior of your core OS functions because you don't know how it will break old applications. If you're interested in Windows development, the The Old New Thing blog goes into detail on issues like this.
A coworker of mine also ran into a similar issue (not realizing something was commented out, thus odd behaviour) with a if 0 .... #endif comment. Vim highlights that correctly too but his emacs setup did not (no idea how stock it was).
Most editors i have used highlight the next line in green as a comment,
however i have come across one that took me over a year to solve, that is
remarkably similar.
//why does this next line not compile??/
x = 0;
because the ??/ operator is a trigraph meaning \
That was never been highlighted correctly any editor I have used.I seriously doubt anyone would care if you did it that way.
(Modern versions of gcc (4.5.2 at least) ignore trigraphs by default but issue warnings saying they ignored one and giving the command line option to honor them. But gcc has long honored the dumber parts of the standard more in the breach than the observance.)
Though I suspect trigraphs being enabled is a very rare source of bugs to begin with, it seems likely that it is still more common than the scenario of active development on platforms that don't support the normal characters (eg the actual development is done on the platform rather than cross-compiled).
This couldn't be any more wrong. First of all, even if there were a performance impact, it would be meaningless compared to the time it takes to perform the system calls required for tmpfile().
Second, the compiler will inline the function call if it can. You can use a regular "inline" function and if you're not convinced it's good enough, then use __attribute__(force_inline) or equivalent. Even if the damn function is not an inline function, it will get inlined if it's in the same translation unit as where it is called (look at the asm output of gcc -O3). In the (not so far) future we'll be able to enjoy link time optimizations and don't have to care about translation units w.r.t. inlining optimizations.
The first thing that sticks out as problematic is the assertion that a level of indirection around tmpfile is going to be slow. There are two ways we can determine if this is true; Try It And See, or read the output of the compiler to see what code it generates. Let's try the second one.
We'll make a file called slow.c with the contents:
int f(void){
return 42;
}
int g(void){
return f();
}
Then we can see what code gcc generates with the -S option: $ gcc -S slow.c
and looking at slow.s. Here's the important part of g (with some annotations removed): g:
.LFB1:
pushq %rbp
movq %rsp, %rbp
call f
popq %rbp
ret
So, we're calling f here. But you don't compile your production code with -O0, so let's try -O3. Here's f: f:
.LFB0:
movl $42, %eax
ret
And here's g: g:
.LFB1:
movl $42, %eax
ret
Notice how we're not calling f anymore; we just get f's body right in our function. So there's no speed cost to writing a function that only calls another function. This is the simplest possible case for an optimizer to optimize, and of course it does.If you want to be explicit, you can always inline g. Then, at g's call site, we see:
main:
.LFB2:
pushq %rbp
movq %rsp, %rbp
call f
movl $0, %eax
popq %rbp
ret
Which is almost the same thing as what -O3 produced, except g's body is copied into its caller instead of f's body being copied into g. (And this is at -O0.)Another case where the thought process goes awry is the guess that there is a preprocessor bug. It's easy to verify, run gcc with -E and see what you get. Here's our test case:
#define foo f
int f(void){
return 42;
}
int g(void){
return foo();
}
Preprocess: $ gcc -E buggy.c
int f(void){
return 42;
}
int g(void){
return f();
}
And look. No bug!So let's move on to the final problem, the weird comment. We'll again see what our preprocessor output looks like on a minimal test case:
#define FILE int
#ifdef _WIN32
# define tmpfile w32_tmpfile
#endif
FILE *tmpfile(void) { return (FILE *) 0 }
FILE *w32_tmpfile ( void ) { return (FILE *) 0 }
void test(void){
FILE *g;
if (code == 200) { // Downloading whole file
/* Write new file (plus allow reading once we finish) */
// FIXME Win32 native version fails here because Microsoft's version of tmpfile() creates the file in C:\
g = fname ? fopen(fname, "w+") : tmpfile();
}
}
We end up with: int *tmpfile(void) { return (int *) 0 }
int *w32_tmpfile ( void ) { return (int *) 0 }
void test(void){
int *g;
if (code == 200) {
}
}
Which looks like our code has suspiciously gone missing. Let's try
removing the comments: int *tmpfile(void) { return (int *) 0 }
int *w32_tmpfile ( void ) { return (int *) 0 }
void test(void){
int *g;
if (code == 200) {
g = fname ? fopen(fname, "w+") : tmpfile();
}
}
And hey, our code is back. Must be something to do with the comments.Anyway, the C toolchain is very simple, so let the computer do the compilation for you when you suspect the compiler isn't doing what you want. Read and understand its output; don't rely on a tool that does something that you couldn't do yourself.
Something I mentioned in that code completion article the other day was "don't rely on your editor to be your brain". This got a lot of downvotes, but this is exactly the problem the author has here. His editor didn't interpret the source code in the same way that the compiler did, and that's what matters.
Learn the language you are using so that you can spot bugs! Don't think something isn't a comment just because your editor doesn't show it in italic orange! Suspect an editor bug, not a compiler bug.
And finally, if you use correct grammar in your comments, this wouldn't have happened:
/* We use our own tmpfile implementation here, since Windows' writes directly to C:/. */I think he probably wants some GUI where the watches automatically update, or where -O3'd code magically executes as though the compiler didn't do any optimizations on it.
And all of that for no benefit - I spend hours learning vim too, but at least there I got flexibility and a supremely powerful editor in return; but there is nothing gdb can do that the Visual Studio debugger can't. And there you just set a breakpoint and press run, while for gdb it takes you a day just to get integration with your editor set up the first time. I'm not sure what you mean with 'flexible' - a debugger is by its very nature interactive, so the typical advantages of text-based tools don't apply. But of course YMMV etc.
I don't code on linux anymore to compare emacs or vim, but if they don't handle it correctly I would submit a bug with them.
You have to put the whole definition of the inner function in the header file. Also it must be static or inline, otherwise the linker will complain about duplicate functions.
Then there is the question of why are we even thinking about the optimization issues about calling tmpfile? Are we doing billions of these calls? Or more on the order of tens of them. But in either case, wouldn't it be evident prior to any optimization or measuring effort that the time taken up by the OS to actually create the file would swamp any gain done by this optimization?
One might then argue that the bugs are 1) using comments 2) attempting an optimization that simple pre-calculation shows no real benefit.
int i = 10;
int *p = &i;
int j = 100/i; // j==10 right? right
int k = 100/*p; // k==10 right?
That last line doesn't compile. int i = 10;
int *p = &i;
int j = 100 / i; // j==10 right? right
int k = 100 / *p; // k==10 right? right
Also, any decent syntax highlighter would have caught the latter problem. The problem in the blog post was much more subtle, because most (all?) syntax highlighters won't catch it. if(NULL != fname) {
g = fopen(fname, "w+");
} else {
g = tmpfile();
}
Better: if(NULL == fname) {
g = tmpfile();
} else {
g = fopen(fname, "w+");
}The else block in this case is executed when "NULL != fname" is false. That's an unnecessary double negative and takes a nonzero amount of mental effort to unscramble. The example I gave reverses this. This would also be acceptable:
if(fname) {
g = fopen(fname, "w+");
} else {
g = tmpfile();
}
(I also don't regard either statement as an "exceptional condition", they both seem equally likely to me.)As others have noted, the moral is to not use C++ '//' style comments in C code or at least hope that you are using a clever editor ;)
The only time I've ever seen backslash's used in C or C++ as a line-break is in huge multi line macros with lots of variables that has been broken up for readability.
It never occurred to me it could be used to do multi line comments but there you are.
(Correctly arguing he is right, then reasonably rebutting this argument, is an exercise for the reader.)
This feature has only been with us as part of the standard since 1999, which in geological terms is merely the blink of an eye. I imagine this is why so many people seem not to know about it.
I mean, if this is a reason not to use C++ style comments, then it seems like a very weak one of many reasons not to use C++, I don't think that was intended.
So I guess most of the C compilers for the target microcontrollers we were working with in later courses would have used the C89 standard
Or rather, value of, rather than dereference by default. Ada got this right, dereference by default, no pointer arithmetic.
The advantage of not abstracting pointers is that it makes low-level programming much easier. Instead of having to write your operating system kernel in assembly, you can write it in a portable language that is much easier to read!
Haskell gets this right. You never write regular Haskell code with pointers but when you need to do some low level stuff, there is a native pointer type and I/O operations peek and poke.
The pass by value semantics of C are well suited for the low level language that C is.
Or do you simply want to change the syntax?