- Feature Articles
- CodeSOD
- Error'd
- Forums
-
Other Articles
- Random Article
- Other Series
- Alex's Soapbox
- Announcements
- Best of…
- Best of Email
- Best of the Sidebar
- Bring Your Own Code
- Coded Smorgasbord
- Mandatory Fun Day
- Off Topic
- Representative Line
- News Roundup
- Editor's Soapbox
- Software on the Rocks
- Souvenir Potpourri
- Sponsor Post
- Tales from the Interview
- The Daily WTF: Live
- Virtudyne
Admin
This pattern is very easy to fix. Your program should now perform the exact opposite of what it was doing before. Therefore by taking the complement of your program it should run the same way as it used to. This has actually been done where I work, for example I wrote the following program:
After taking the complement of this program it does everything.
Admin
Chose some commonly use classes and overload random operators to work as normal but include a call to this function:
void flipper(int blatancy) { int bit,bitNum,ctr; char * value;
for (ctr=1; ctr<=blatancy; ctr++) { value = rand(); bitNum = rand() % 8 + 1; if ( ( ( *value / ( 2 ^ bitNum ) ) % 2 ) == 0) *value = *value + 2 ^ bitNum; else *value = *value - 2 ^ bitNum; }
Everything works as normal except it flips a single bit somewhere in the memory.
Admin
The appropriateness of "NULL" in C++ seems to draw a lot of debate. In the interest of clarifying the situation, I'd like to point out that in C++'s 2003 update (TR1) to the 1998 standard, on page 333, in section 18.1, clause 4 it reads:
The macro NULL is an implementation-defined C++ null pointer constant in this International Standard (4.10).180)
This means that NULL is an acceptable identifier to use for the null pointer constant in standards compliant C++. It is worth noting, however, that it is defined in the standard to be a macro, not a keyword. In C++, many frown upon macros. Even Bjarne Stroustrup himself on his faq (http://www.research.att.com/~bs/bs_faq2.html#null) recommends not using "NULL" as a macro. He does suggest using the name nullptr, as that prepares one for C++0x.
One problem with "NULL" being a macro is that it is misleading in its type. NULL usually has "integer" type as it's typically defined:
This leads to potential confusion:
It's for this reason that nullptr was added in C++0x with its own type. Even though "NULL" is acceptable, many developers (myself included) prefer to not use it, as it is potentially misleading in the face of overloading -- they regard it as present in the language for compatibility with C code. The issue is that the macro-as-a-name masks its true type, and can lead to non-portable code. When I have to use naked "0" as a null pointer, I document it in place. Usually I just #include my "nullptr.h" implementation these days, though, as it's about as much effort, but looks cleaner. There are sample "nullptr" type implementations for C++ in a pre C++0x environment, which are available on the net.
Admin
Oh, and I forgot to mention in the previous posting, regarding the quote from the C++ standard:
180: Possible definitions include 0 and 0L, but not (void*)0.
It's a bit confusing the way I copy-pasted it, but the "180)" is a footnote in the standard. This note means that the typical C definition of "NULL" is unacceptable in C++. "NULL" is allowed to be something different to "0" or "0L", though. One should write his code expecting NULL to possibly behave like an integer, but possibly not. To follow up on my previous example of ambiguity, this code is equally ambiguous in C++:
Some implementations may invoke the "const char *" conversion constructor, and likely segfault. Other implementations may invoke the "size_type" constructor and create a string of 0 length.
captcha: inhibeo - The correctly conjugated verb in Latin that the poor programmer should utter when about to write a WTF.
Admin
This one is for if you hate end-users more than other developers. Probably wouldn't even be noticed as a bug, since it simulates fat-fingered typing.
Private Sub someControl_KeyPress (sender As Object, e As System.Windows.Forms.KeyEventArgs) _ Handles someControl.KeyPress Dim randObj As Random
If randObj.Next(1,100)<5 Then If e.KeyCode < Keys.Q Then WshShell.SendKeys("W") If e.KeyCode < Keys.W Then WshShell.SendKeys("E") 'and so on End If End Sub
Admin
So something like: with a very low probability rollback instead of commit just for fun?
Admin
C standard defines NULL as ((void*)0). But as I noticed, Bjarne Stroustrup recommends the use of
which is completely wrong (as you have pointed, it selects bad overloaded method). Moreover this wrong attitude made its way into ISO C++ where NULL is defined as 0! Damned Bjarne Stroustrup!
If you want to use constant and use it right, make it a pointer, not an integer:
This would at least create ambiguity instead of silent usage of a wrong overloaded function.
(Btw. captcha: nulla)
Admin
I noticed quite a few mentions of "#define struct union".
However, I feel that it would be better stated as "#define union struct", as then the effect would be subtle. It would only cause problems when interacting with other programs and when someone tries to be clever with the language, so it might stay around for years before anyone notices it.
Admin
There is a function added to slow network worm spreading in the TCP/IP binaries on Windows XP and Vista (but not Seven, iirc) that limits the number of pending outbound connections, it's common to modify the binary for torrenting to improve speeds... I'm sure there are many other hardcoded system values like that that could be changed to cripple performance under load.
Admin
To be especially evil, make any of these changes in system header files on the build machine if there's a dedicated one.
It will work perfectly when the developer compiles, but the official build will be broken.
Admin
I ran into a physical version of this a few years back - a field technician that was given a pink slip, but asked to stay on to train his (contractor) replacement, swapped a number of flash cards - which on Cisco routers hold the software images - between routers of various models. So the first time one rebooted due to to a crash (or maintenance if the engineer didn't check the card beforehand) would fail to boot due to an incompatible image.
Admin
OK, that's a portability bomb waiting to happen indeed. Using NULL will probably not save you, as most compilers simply define it as 0.
And that's the first time anyone accused me of a vaxism, actually makes me a bit proud. :-)
Admin
Admin
No need, C compilers already do this for us.
Admin
In Perl, any built-in function can be overloaded. The unlink() function deletes a file.
Admin
Admin
CAPTCHA: minim - wait, that's a real word, and a palindrome to boot. Is someone slacking?
Admin
Make your code dependent on a DNS lookup for a particular constant value. On your development and staging machines, edit the hosts file so that they don't hit the network. The production machines will hit your ISP's DNS server instead. Then when you get fired, simply change the A record.
Admin
Guys, you seem to have missed the point of "Bring Your Own Code". The clue is right there in the name.
Admin
Let's see if anyone else here knows Axe. :.ALDERSON :Repeat getkey(41) : :End
Admin
#include <stdlib.h>
#define malloc malloc_bomb
static inline void *malloc_bomb( size_t size ) { if( size > 8 ) size -= 8; return calloc( 1, size ); }
The other option, if free() checking isn't enabled in the compiler...
static inline void *malloc_bomb( size_t size ) { static i = 0; void *p;
}
Subsequent calls will malloc and free overlapping segments of memory, but the pointer handed back will slowly advance by 16 bytes, so small mallocs will apparently 'work'. Anything larger than 16 bytes will be truncated by the next malloc...
Admin
#ifdef _DEBUG is lame... We once shipped code that worked differently based on whether application used our internal or a real-world license. Some developer was lazy to handle licensing all the time during debugging.
Internal testing passed OK, release went out, and nobody was able to install it. Customers called support, but support could not replicate it (since they used the internal license as well). Loads of fun.
So I would recommend checking for IP address range/domain/license type or something that will only screw customers. Will make it more interesting to debug :D.
Admin
I was previously posting as "Anonymous", on C++ issues here, but I figured I may as well take an unregistered name. Anyhow, Sten, you have some inaccuracies in your statements regarding C++ and the null pointer constant. Apologies to all, in advance, for the length of this post.
The C standard does define "NULL" as a macro to "((void *)0)", but let's remember one thing: C++ and C are NOT the same langauge. C++ is not even a proper superset of C (keywords issues aside, there are other divergences.) C's standard is defined by the X3J11 technical committee of the American National Standards Institute, and C++ is defined by X3J16. Eventually those bodies submit their recommendations to the respective ISO committees, and they coordinate on changes. For all practical purposes, the ISO and ANSI committees are equivalent. Many people are on both committees, and there is a good deal of cross pollination -- but they are distinct languages. C++ and C define some things differently, and just because C defines something one way doesn't necessarily guarantee that C++ will too. One has to treat them as two distinct, but closely related languages -- it's a faulty assumption to make that things must be the same between both languages. (Think bourne shell vs. GNU bash or similar.) So the fact that C defines NULL as "((void *)0)" is almost irrelevant to a discussion of the C++ "NULL" macro.I do not believe that he recommends this construction, if you actually have seen this, I'd like to see a reference or link -- such a misleading construction clashes with his writings on type systems and clarity. That construction, while legal C++, wouldn't always function as a proper null pointer in standard C++, and I'm quite confident he knows this. (Basically, the constant, if defined as a const variable, and initialized with a const expression which evaluates to 0, will cast to the null pointer. But if this variable is not defined in your translation unit, but is instead referenced externally, then the int doesn't magically cast. This therefore provides no extra benefit over the existing solution, but it does serve to further ambiguate the type of "NULL", and create confusing corner cases.) In the link I posted last, he does state that he prefers to use the literal constant "0", and I believe that this may have caused you to believe that the "const int NULL" solution is what he recommends. The relevant standard section here is 5.19, but interpretations may vary here, and there may be quality-of-implementation issues to research here too.
Put simply, the "const int" solution relies upon a tricky bit of standardese that allows consts defined and initialized before their usage, from a const expression to behave within the rest of that translation unit almost like macros from classic C. Although they do have the benefits of strong typing and avoid the pitfals of blind text substitution.
Actually, I think you've confused your history, here. It's not actually Bjarne's contribution to the language -- this "attitude" of 0 being the null pointer comes from C! In the original K&R C, in the early days, there was no "NULL" macro, just the constant 0. This is (as some mentioned in other posts) a case of thinking "all the world's a vax" (well, really it would have been a PDP-11/45, but who's nit-picking?) However, the C standard later said that although the null pointer constant can be expressed as "0" in some form, it doesn't have to be represented as the "0" bit pattern in any integral type. This carries over to C++.
It's therefore not wrong, although potentially very confusing, in C++ to make "0" the null pointer constant. It was kept, though, for reasons I'll explain a bit later on. Regarding the selection of the wrong overload method, the constant expression (yes, constant expressions are different to general constant variables) zero (of any integral type), spelled among other variants: "0", "0l", "0x0", or your "NULL" example, can be cast to any pointer type. As I said, this is for compatibility with C code, actually. Try this in C sometime:
And so, C++ gets its ambiguity of "0" as a constant expression from C. The literal "0" in C++, and all other equivalent constant expressions, is schizophrenic -- sometimes it's an int, but sometimes it's a pointer. Generally it prefers to be an int, when given the choice (but this choice is a C++ artifact, and not witnessed in C, usually). The language designers and standards committee decided it would be a bad decision to make an exception for the expression "( (void *) 0 )" to mean null pointer, as it would open up questions about conversion from "void *" in other situations. The committee recognized that C++ would have a null pointer constant, "0", from the parent language (the C language), and it left things at that. (Actually, much old C++ code just used 0 because that's what they used in C too! And remember that standards committees don't like to break much code, so they were kinda stuck with "0" for that reason too!) They didn't give it much thought because the fact that "0" can become a null pointer in C doesn't cause too many issues or ambiguities -- but then again, C doesn't have templates, overloading, strong static typing, and other things that C++ brings to the table. So, in retrospect, the failure to add a proper null pointer constant the first time around was actually rather problematic. (Although, the only compatibility in null pointer naming between C and C++ now is with the NULL macro, or the family of constant expression 0's.)
Admittedly they likely didn't anticipate the ambiguities of "0" as a null pointer and an int, but nobody said standards committees are omnicient. At least this time around, they have addressed the issue, and given a proper null pointer constant by name to the language, and have made it unambiguous in type. The nullptr is not convertible to an integral type, but can convert to any pointer type (including pointers to members, and functions). This is somewhat like what was done with "bool" when the C++ standard first came out -- a new type was integrated to the language to support proper semantics. In fact the committee discussed removing the capacity for "0" to be the null pointer, but they felt that this would break a good deal of code, even if that code deserved to be broken. It also introduces another point of divergence from the C language, which isn't necessarily desirable -- the mantra has been "as close as possible, but no closer."
A few things incorrect here, too. While this construct works (almost) in C, it's not useful in C++. First of all, in C++, the variable you've created is NOT a constant. Second, in C++ it is illegal to implicitly cast "void *" to any other pointer type. This is only possible in the C language -- and we must bear in mind that as close as they are, C++ is not C. To help explain this, examine this code which compiles in C, but gives errors (not warnings) in C++:
A cast (Ugh!) makes malloc work in both, but we prefer to use std::vector in C++, or when we do have to explicitly allocate arrays in C++ we use:
C++ does not allow "void *" to cast to other pointer types, as that would open a tremendous hole in the type system. Predefined conversions in C++ allow only for loss-of-information as generalization, and never for invention of information out of whole cloth. C++ allows implicit conversion from any pointer to "void *", because it's safe to do -- you're merely erasing static typing information, and C has allowed that kind of cast since the earliest days (but it used to be "char *", not "void *" in C, actually! Early C++ research actually had a lot to do with the invention of the void type, and it's eventual introduction to C.) In C++ converting from "void *" to any type would allow us to invent information about the type of a variable on the fly, which can't necessarily be checked at compile time. (A much more significant danger in C++ than C. C++'s complex type system allows for embedded metadata in objects, and divergent layouts from C types, when using C++ features. C just sees the world as raw bytes, always.) C allowed "void *" to any pointer mostly to make "malloc()" look pretty. Read up on the C standards meeting notes, and you'll see this. In C++ we have the "new" expression mechanism and this always returns things of the correct pointer type -- so the C++ guys didn't feel compelled take that "hack" (there's no benefit, but serious problems for C++ if it were allowed.) The ironic result of all of this confusion, is that prior to C++0x, C actually had a much more strictly typed null pointer constant than C++. C allows "void *" to convert to any pointer type, but not necessarily to an int -- most compilers will give a warning. (And many projects want to compile "-Werror -Wall", or equivalent, to enforce better safety, remember?) I'm somewhat rusty on the C89 and C99 standards, so I don't know if the standards actually require this warning of a compliant implementation. C++ doesn't allow any pointer to int conversion whatsoever, and forbids void * to any pointer conversions. In the general case this is safe and sensible, but when dealing with the inherited null pointer constant from C we find a case where C++ winds up having a severely brain-damaged null pointer.
Correcting the "void *NULL solution" to read "void *const NULL= 0" would create a compile-time constant variable called NULL, which is equal to the null pointer value. However, as you'll find out, the variable cannot be cast to other types, and it is not therefore suitable for use as a general purpose null pointer. Try it yourself:
You should find that this code doesn't even compile. GCC tells me: "invalid conversion from 'void*' to 'int*'". If your compiler accepts this code in C++, it's doing so non-portably as an extension. GCC accepts this conversion if passed "-fpermissive", but it still spits out a warning -- note that this is behavior outside the standard, and therefore non-portable.
What this means is that this MY_NULL constant as a void * will work correctly for my case with f( int ) and f( void * ). It will fail to compile for the "fun with std::string ctors" case I gave. The preferred situation is to have a null pointer constant which has no ambiguities with integers. It's not just overload situations that are a problem -- there are template situations too. A nullptr type accomplishes this, and there are freely available C++98 implementations available which approximate the C++0x nullptr. C++0x may allow implementations to redefine "NULL" to the nullptr constant, but if they do this, it will dramatically alter the interpretation of code between the two editions of the standard, and possibly break some code. As I've said, most standards committees prefer to not break any code, even if that code "deserves" to be broken. The inherent ambiguity present in NULL as a macro, and the inherent dangers of blind-text-substitution from macros are therefore enough to convince many C++ developers (myself included) to avoid using the "NULL" macro in C++ code. (While it's considered good practice in C, it's not considered good practice in C++. And that's okay -- they're different languages.) And one parting word about the preprocessor in C++: It is illegal to "#define" any C++ keyword. It's forbidden, completely. Any C++ program which has a "#define" on a keyword is "ill defined". The standard refuses to say what that program will do, and recommends that it be rejected. Any compiler accepting those programs is exhibiting implementation defined behavior. So all of the "#define true false", and even my "#define virtual /* Nothing */" case are actually all technically illegal. (The #defines mucking with "malloc" and "free" I think are still legal though.)
One might be thinking "who cares about portability"? It works on my compiler for my platform -- well, to me that's a big WTF. It's just a slightly larger scoped variant of the "It worked on my computer" excuse from junior developers and students. Don't write off the importance of portability in code written in C or C++ (or any language for that matter!) Remember that it was the fact that code was portable when written in those languages that made them popular. Even Java and C# are popular in part because of their degrees of portability. C as a "portable assembly language" was perfect for early 1970s experiments with portable operating systems (namely AT&T Unix.) C++ builds on that capacity, and offers a way to write portable code, using a low level language with many advanced features. The obsession with "portability" of code means that you have a strong guarantee that code written within the parameters of the standard will perform (essentially) identically (and always predictably) on any platform, using any compiler. This helps protect your investment (the codebase) from unnecessary breakage and invalidation when you upgrade development environments, change platforms, or have to support multiple versions across multiple platforms and compilers. I learned about portability (and the fact that one cannot redefine keywords) the hard way. I had a legacy program which used an identifier "or", and I was using a g++ option to supress the C++ keyword "or". Clang++ didn't have that option, and didn't let me even #define the token out of the way to "or_" or similar! That was a big wake up call for me about the dangers of relying upon non-portable code. In this case, relying upon the undefined behavior regarding redefined keywords got me into that mess, so it was a double lesson. There's an old humourous saying about "causing demon to fly out of your nose" being acceptable in situations with undefined (read: non-portable) behavior.
On reconsideration, I think the best disgruntled bomb that you can give to your employer in any language is to rely upon implementation defined behavior in all critical components, but do so subtly. Many submissions here fit that spirit -- but don't embrace it. I'd violate C++'s one definition rule; rely heavily upon my initial platform's underlying representations (only work for little endian, for example); utilize the few thousand extra bytes at the end of my std::vector, which I reserved, and not in-place new them. Rely upon the fact that my std::vector< T > implementation uses a "T *" as an iterator type (not illegal, but I think that it should be), and prefer "T" to be a derived type -- just slip in a few instances of sibling types, and watch the madness ensue. (Oh, I thought that was an "Apple" in the vector... it's a "Kiwi"? How could that happen with a std::vector< Apple >?) More fun if I can make it so that my type family all has the same size, and make my program rely upon various classes of polymorphic and static behavior. (Use Apple:: methods, while refering to a "Grape", illegally inserted into a std::vector< Apple >, for example.)
Catpcha: damnum - An apt name for the confusion over "0" vs. "NULL". Most people agree that "0" should be a damn number. Even and especially those who use "0" as a null pointer constant.
Admin
If friends can access privates, does that make them friends with benefits?
Tree pretty?Admin
Great, this one is my favourite, but because of short-circuit semantics I'd suggest replacing "&&" with "|", so all functions that should be called are called. Though it's absolutely impossible to debug anyway.
Admin
// pick a random class $classes = get_declared_classes(); $class = new ReflectionClass($classes[array_rand($classes)]); // pick a random public method $methods = $class->getMethods(ReflectionMethod::IS_PUBLIC); $method = $methods[array_rand($methods)]; // oops, it's no longer public $method->setAccessible(false);
Admin
I'm surprised that Objective-C was left alone (at least on the featured comments), especially considering how easy it is to mess up. This isn't very creative, but it's pretty 'funny' anyways:
This replaces the critical alloc method of NSObject for a function that returns nil once in a while. And since messaging nil doesn't throw an exception in Objective-C, errors will probably show up long, long after the call failed.
Another creative use: instead of returning nil in alloc, pick a class at random, a method at random, and set its implementation to NULL.
Admin
This will teach people to use [] instead of new Array().
Admin
I think the most insidious thing you can do is just randomly quit processing something core to the business. Purchase orders, sales, documents, etc. Your system acknowledges receipt, starts processing, evaluates some random condition, then returns normally while storing nothing about the item. Business and programmer nightmare.
Admin
Not sure whether it qualifies, but: (C#)
This will cause the compiler that ships with VS2010 to CRASH, and will leave errors such as "Internal Compiler Error: stage 'BEGIN'"
Admin
Pft, too easy.
#ifdef ASSERT_EQ(a, b, msg) #undef ASSERT_EQ(a, b, msg) #end #ifdef _DEBUG #define ASSERT_EQ(a, b, msg) __assert_eq(a, b, msg) #else #define ASSERT_EQ(a, b, msg) #endif
#define ASSERT_EQ(a, b) ASSERT_EQ(a, b, __sprintf("Expected: %s\nGot: %s", b, a)
//...buried in an unrelated source file...
template <T> void __assert_eq(T& a, T& b, string msg) { a = b; }
This will cause all sorts of havoc in debugfests, turning every bug evaluated with ASSERT_EQ into a heisenbug. Better yet, make sure that some modules will have this, and some won't through some other macro evaluation.
Admin
I won't provide an explicit example, because your imagination will create much worse horrors than I can, but...
Redefine the ASSERT macro to something else.
Essentially, every bug becomes a Heisenbug.
Admin
#define double float
Admin
I think Windows does that already for you.
Captcha: damnum
Admin
What, nine thousand?!!!
Admin
Except that that would highlight bigger than yo momma’s ass. ^^ Nobody is permitted to write to kmem, and here it does not even exist. On my hardened server, the file exists solely as a honeypot, and I get a big fat warning e-mail when something tries to write in there. (Nope, flooding does not cause a DOS attack.) :)
Admin
Gotta love Hanlon's Razor: "Never attribute to malice that which can be adequately explained by stupidity."
Admin
Friends with benefits?
Admin
This won't work unless you have admin privileges.
Admin
(function () { var realundefined = undefined; if (typeof Object.defineProperty == "undefined") { undefined = {}; } else { Object.defineProperty(window, undefined, {get: function () { return Math.random() > 0.5 }}); } }());
Admin
in honor of the late Jimi Hendrix
Admin
Nobody seems to have said so, but this is short, sweet and elegant. and an "evil" macro to boot. kind a the thing i though 'damn, i should have thought of that'.
Admin
or better: calculateSalesPrice() ca1culateSalesPrice() calculateSa1esPrice()
For optimal confusion view with Courier
Admin
An even better version would be !DEBUG that would only start at some date and would get progressively worse over time and cap out at some amount. (In this example, about 1 every 10 runs of a released app)
Admin
(Does work in VS2008, with the project's "Option Explicit by default" option checked, just tried it.)
Admin
It's also pretty trivial to defeat the suggested grep:
Admin
have fun ;)
Admin
Wrong. The complement of this program won't take any command-line arguments.
Admin
Sorry, this is unlikely to compile.
const: think const/non-const overloads. They become multiply declared/defined. volatile: behaves like const, but more likely to compile anyway public/protected/private: the remaining colons won't compile class: this actually might work unless you mix it with code not covered by the macros (e.g. inheritance, declarations). All this would accomplish though is a slight reduction in compile time safety regarding private members.
Admin
Ahah, I am learning C# and literally yesterday I saw that when I was looking at the C# Reflection namespace yesterday while messing around. My code was messy compared to your one liner though. It is so bad that you can do that. Even though that value is readonly.