Take the 2-minute tour ×
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

Your task is simple. Write a program that should obviously produce an error on first glance either when compiled or run, but either doesn't or produces some other unrelated error. This is a popularity contest, so be creative.

share|improve this question
6  
hmmmm.... this one is a brain teaser. +1 –  Tim Seguine Mar 6 at 22:30
 
Sort of cheating, but here’s an instance from TeX.sx where a simple "Hello World" was throwing errors: tex.stackexchange.com/questions/164043/… –  alexwlchan Mar 7 at 0:30
2  
@alexwlchan Isn't that the opposite of what we want here? –  arshajii Mar 7 at 2:56
 
@arshajii: yes, of course. *facepalms* My mistake. –  alexwlchan Mar 7 at 3:20
 
Wish I could find it... there was an old PL/I example which included a statement along the lines of "if if if = then then then = else else else = if then else ..." (PL/I allowed using its keywords as variable names, and had a conditional expression similar to C's ?: that also used the if/then/else keywords...) –  keshlam Mar 7 at 5:43
show 2 more comments

48 Answers

up vote 140 down vote accepted

C++

Make sure you compile the following code in standard conforming mode (for example, for g++ use the -ansi flag):

int main()
{
  // why doesn't the following line give a type mismatch error??/
  return "success!";
}

How it works:

The ??/ is a trigraph sequence that is translated into a backslash which escapes the following newline, so the next line is still part of the comment and therefore won't generate a syntax error. Note that in C++, omitting the return in main is well defined and equivalent to returning 0, indicating a successful run.

share|improve this answer
4  
I feel like the first answer just insta-won this right off the bat. –  Aerovistae Mar 7 at 20:34
1  
64 votes... Nice number –  Jwosty Mar 7 at 23:07
 
It's also valid in C99. –  R.. yesterday
add comment

Ruby

Always a fan of this one.

x = x

No NameError. x is now nil.

This is just a "feature" of Ruby :-)

Here's a more mundane one that's gotten me before:

x = 42

if x < 0
  raise Exception, "no negatives please"
elseif x == 42
  raise Exception, "ah! the meaning of life"
else  
  p 'nothing to see here...'
end 

Prints "nothing to see here."

It's elsif, not elseif. (and it's certainly not elif - woe to the wayward python programmer (me)!) So to the interpreter elseif looks like a normal method call, and since we don't enter the x<0 block, we go straight on to else and don't raise an exception. This bug is incredibly obvious in any syntax-highlighting environment, thankfully (?) code golf is not such an environment.

share|improve this answer
2  
You got me. I've done both Python and Lua before, and now starting on Ruby. Lua uses that one. –  Riking Mar 7 at 9:07
add comment

JavaScript

var а = 100;
if (typeof a !== 'undefined') throw 'This should always throw, right?';
console.log('How am I still alive?');

Here's how it works:

The first a is actually an а (that is, Cryllic Unicode "a").

share|improve this answer
5  
This trick can be applied to any languages that accept Unicode token (e.g. Java, C#). –  n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ Mar 7 at 1:59
32  
@n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ , exemplified by your username –  TheDoctor Mar 7 at 3:03
4  
too obvious solution –  thepirat000 Mar 7 at 4:35
5  
too obvious for anyone that's come across it before. I'm sure plenty of newbies and so-call "web experts" may get tripped up on it. –  Thebluefish Mar 7 at 12:40
14  
Obvious? So you always look at your variable names through their Unicode numbers instead of by what they look like? You might notice it if you search for "a" (or "а"?) and fail to find what you expect, but when simply reading, you can't see it (at least in the font shown here). –  Tim S. Mar 7 at 17:06
show 5 more comments

C?

Pretty normal code here...

void main() = main--;

It's Haskell, not C. It defines a function named "void" that takes two arguments. The first is named "main" and if the second (unnamed) is an empty tuple, it returns the "main" variable. "--" starts a comment in Haskell, so the ";" is commented out.

share|improve this answer
8  
So in other words, it's cheating? –  Mr Lister Mar 7 at 14:33
22  
Cheating is normal in code-challenge competitions. We call it creativity. :P –  Joe Z. Mar 7 at 15:42
10  
I'd call this one cheating, not creativity. You have to define the environment you're running in before you can even consider whether some code will error or not. Otherwise I could just give you the line noise that is Malbolge and ask you if it compiles. –  Tim S. Mar 7 at 17:11
3  
It's just supposed to make you stop for a second and go 'hey can you do that?' :) –  intx13 Mar 7 at 18:17
4  
@JoeZ. It might look like perl in some cases. –  user80551 yesterday
show 1 more comment

bash

#!/bin/bash

[ 1 < 2 ] && exit

for i in `seq 1 $[2 ** 64]`
    do "$0" | "$0"
done

while [[ false ]]
    do :
done

if maybe
    do [: [: [: [: [; [; [; [; ;] ;] ;] ;] :] :] :] :]
fi

Results

  • You might expect the script not to produce any errors at all, since it exits after the first command. It doesn't.

  • You might expect the typical error messages caused by an ongoing fork bomb due to the for loop. There's no fork bomb.

  • You might expect bash to complain about the missing maybe command or the whole bunch of syntax error inside the if block. It won't.

  • The only error message the script might produce ends in 2: No such file or directory.

Explanation

  • [ isn't special to bash, so < 2 performs, as usual, redirection. Unless there is a file with name 2 in the current directory, this will cause an error.

  • Due to that error above, the command before && will have a non-zero exit status and exit will not be executed.

  • The for loop isn't infinite. In fact, there's no loop at all. Since bash cannot compute the 64th power of 2, the arithmetic expression's result is 0.

  • [[ false ]] tests if false is a null string. It isn't, so this while loop is infinite.

  • Because of the above, the if statement never gets executed, so no errors get detected.

share|improve this answer
18  
Please don't change the bold text inside the spoilers into code. I don't know how it looks in other browsers, but it's unreadable in mine... –  Dennis Mar 7 at 3:21
1  
Ooh, nested spoilers. –  Mr Lister Mar 7 at 14:26
2  
@Dennis: That's a known bug. –  Ilmari Karonen 11 hours ago
 
@IlmariKaronen: Looks like I'm getting forgetful. I've upvoted that bug report almost 2 years ago... –  Dennis 11 hours ago
add comment

JavaScript

When I was providing the following code I was told many times "It must be a typo! How can it work?".

console.log( 42..toString(2) );

The description below was copied exactly from one the recent cases.

As you probably know, in JavaScript everything except literals is an object. Numbers are objects as well. So theoretically (and practically) you may get properties or call methods of any non-literal via dot notation, as you do 'string'.length or [1,2,3].pop(). In case of numbers you may do the same but you should keep in mind that after a single dot the parser will look for a fractional part of the number expecting a float value (as in 123.45). If you use an integer you should "tell" the parser that a fractional part is empty, setting an extra dot before addressing a property: 123..method().

share|improve this answer
4  
As a lua guy, I was expecting 422 –  mniip Mar 7 at 9:40
1  
Haven't seen this usage before, very neat. –  Nit yesterday
add comment

Java

class Gotcha {
    public static void main(String... args) {
        try  {
            main();
        } finally {
            main();
        }
    }
}

No stack overflows here; move along.

At first glance, this should produce a StackOverflowError, but it doesn't! It actually just runs forever (for all practical purposes at least; technically it would terminate after a time many orders of magnitude longer than the age of the universe). If you want to know how/why this works, see this. Also, if you happen to be wondering why we can call main() without arguments when the main method generally would need a String[] argument: it's because we've declared it to be variable-argument here, which is perfectly valid.

share|improve this answer
1  
As the question you linked explains, it doesn't run indefinitely, but instead for an extremely long time. –  Kevin yesterday
 
@Kevin Let's not get unnecessarily pedantic here; "longer than the age of the universe" is, for all practical purposes, "forever". –  arshajii yesterday
2  
You say "No stack overflows here", when in fact, the system keeps throwing stack overflows continuously, and will eventually throw a stack overflow exception. (as you mention, eventually could be a very very long time) And, it depends on the stack depth. On a smaller VM, or embedded system, the stack depth could be a lot smaller. –  McKay 11 hours ago
 
@McKay That statement is clearly a mere throwaway line, not meant to be taken literally. The OP asks for a program that looks like it should produce an error, but doesn't. In the general case, the answer above satisfies this requirement. Sure, we can concoct an obscure situation where it doesn't, but that doesn't invalidate the answer. I hope that you will reconsider your downvote. –  arshajii 11 hours ago
 
@McKay By the way, assume that stack size is small (e.g. 100 as opposed to the normal ~10,000), and we can still make 10,000,000 calls per second. Then the total running time comes out to 4,019,693,684,133,147 years -- still many orders of magnitude larger than the age of the universe. –  arshajii 11 hours ago
show 2 more comments

Perl

use strict;
use warnings;
Syntax error!
exit 0;

Source and explanation: http://stackoverflow.com/questions/11695110

share|improve this answer
32  
Perl programs generally look like errors. –  ugoren Mar 7 at 17:40
add comment

VBA/VB6

Private Sub DivByZero()

    Dim x() As String
    x = Split(vbNullString, ",")

    Debug.Print 1 / UBound(x)

End Sub

Splitting an empty comma delimited string should give an empty array. Should be an obvious division by zero error, right?

Nope. Surprisingly, when any zero length string is split the runtime gives you an array with a lower bound of 0 and an upper bound of -1. The code above will output -1.

share|improve this answer
 
@minitech Actually, if you pass an empty array to UBound it will give you a Subscript out of range error. –  Comintern Mar 7 at 5:30
 
… well. I take that back. VBA =/ –  minitech Mar 7 at 5:32
1  
@minitech Yep. I understand this was a bug in the original implementation of Split in VB6. In .NET they intentionally "added" (or maybe documented is the better word) the behavior for empty arrays returning a UBound of -1 in order to maintain backward compatibility with all the VB6 code that took advantage of this hack. Splitting a null string is the only way to natively get this array in VBA/VB6 without Windows API calls. –  Comintern Mar 7 at 5:36
add comment

C++

#include <iostream>

int succ(int x)
{
  return x + 1;
}

int succ(double x)
{
  return int(x + 1.0);
}

int succ(int *p)
{
  return *p + 1;
}

int main()
{
  std::cout << succ(NULL) << '\n';
}

Why?

NULL is an intergal constant, so it matches the int overload strictly better than the int* one. Still, most programmers have NULL associated with pointers, so a null pointer dereference can be expected.

share|improve this answer
5  
Thankfully, C++11 allows implementations to define NULL as nullptr, and implementations that do so (none yet that I know of, but I do expect them) will give the expected segmentation fault. –  hvd 2 days ago
add comment

Java

Probably too obvious.

public static void main(String[] varargs) throws Exception{
    char a, b = (char)Integer.parseInt("000d",16);
    // Chars have \u000d as value, so they're equal
    if(a == b){
        throw new Exception("This should be thrown");
    }
}

What?

Throws a syntax error after \u000d. \u000d is the unicode for a new line. Even though it is commented out, the Java compiler treats what is after this as code since it isn't commented out anymore.

share|improve this answer
1  
your varargs are not varargs ;) –  Navin 2 days ago
 
The question was "code that looks like it fails but doesn't", not "code that looks that it fails, but does so in a different way". Having a syntax error instead of an exception is still an error. –  Nate Kerkhofs 16 hours ago
2  
I think you should read the original question again: "or produces some other unrelated error." –  Tom Verelst 16 hours ago
add comment

C#

class Foo
{
    static void Main(string[] args)
    {
        Bar();
    }

    static IEnumerable<object> Bar()
    {
        throw new Exception("I am invincible!");
        yield break;
    }
}

Because the Bar method does a yield, the method doesn't actually run when called, it returns an enumerator which, when iterated,s runs the method.

share|improve this answer
 
At Last... Here is the FOO and BAR :) –  VVK 15 hours ago
 
That's what foo and bar are for ;) names of things that don't actually matter. –  McKay 11 hours ago
add comment

Objective-C

Not a big deal, but it has surprised me while trying to put a link inside a comment:

http://www.google.com
        return 42;

http is a code label here, such labels are used in goto instructions

share|improve this answer
 
This should work in any C-like language that supports // comments. –  Ilmari Karonen 10 hours ago
 
Yeah, probably, I just wasn't sure while posting –  Piotr 4 hours ago
add comment

JavaScript

if (1/0 === -1/0) {
  throw "Surely there's an error in here somewhere...";
}

How it works:

There's positive and negative infinity in JS, and no error for dividing by zero.

share|improve this answer
1  
You should be able to do some tricks with NaN too... –  intx13 Mar 7 at 20:01
1  
meh, this happens in any language with floats. –  Navin 2 days ago
1  
@Navin: in any language with floats where division by zero doesn't cause an error. –  nwk yesterday
 
A.k.a. JavaScript. –  Aerovistae 10 hours ago
 
@nwk The IEEE standard for floats says division by zero must be an inf. I don't know of any languages that change this. –  Navin 1 hour ago
add comment

CoffeeScript

What? No error? Yep, this code does not have any bugs, why it would?

? followed by a space is operator that calls a function, but only if it exists. JavaScript doesn't have a function called What, therefore the function isn't called, and its arguments are simply ignored. The other words in the code are function calls that actually aren't called, because What function doesn't exist. At end, ? is existence operator, as it is not used in call function. Other sentence enders, such as . or ! would not work, as . is for methods, and ! is not operator (which cannot be used after an identifier). To read how CoffeeScript converted this to JavaScript, visit http://coffeescript.org/#try:What%3F%20No%20error%3F%20Yep%2C%20this%20code%20does%20not%20have%20any%20bugs%2C%20why%20it%20would%3F.

share|improve this answer
add comment

PHP (40 bytes)

<?for(;;$e.=$e++)foreach($e::$e()as&$e);

This was the answer I gave in this question: Insanity Check Program

The idea was to make a code that produced errors.

The 1st error that we will think of, is a syntax error.

There are no syntax errors...

Other would be that the class/function doesn't exist.

It doesn't run that far...

Other would be a time-out or a memory overflow, but, again, it doesn't reach that far...

Test the code here: http://writecodeonline.com/php/ (remove the <? on the beginning to test).

share|improve this answer
1  
This is a popularity contest. No need to cramp up ur code to save bytes. Just reformat it for better readability ;) –  Songo Mar 7 at 3:31
 
I will add a readable version later. I used the same exact answer and didn't edited it at all. –  Ismael Miguel Mar 7 at 10:12
 
foreach(e()as&$e); is the core of this solution. e() is just to keep the syntax-checker going and &$e after the as is what causes the failure. –  TheConstructor 2 days ago
 
Actually, everything play an important role. –  Ismael Miguel 2 days ago
add comment

Javascript

5..toString();
5 .toString();

Gives: 5

Whereas:

5.toString();

Gives SyntaxError

How it works:

JavaScript tries to parse dot on a number as a floating point literal

share|improve this answer
11  
How did it happen that you posted exactly the same case as I did an hour after me? –  VisioN Mar 7 at 11:21
1  
Hey Vision, sorry but i didn't check your answer. I also added a case with space. I read this once on javascript garden nothing else. –  Sumeet Kashyap 2 days ago
add comment

C

Strings and arrays in c can be pretty confusing

main(){
  int i=0;
  char string[64]="Hello world;H%s";
  while(strlen(&i++[string])){
    i[' '+string]=string[i]-' ';
  }
  5[string]=44;
  return printf(string,'!'+string);
}
share|improve this answer
5  
its hard to read, but i don't know what kind of error people are expecting from this –  Bryan Chen Mar 7 at 2:40
3  
I just wanted to remind people of valid but unconventional notation - make of it what you will. I would certainly look three times before saying this is valid. First of all, expressions like 5[string] are not well known to a casual coder and defies logic of array indexing. Secondly, ' '+string looks like addings 2 strings, but with wrong type of quotes. And thirdly, &i++ looks like address of an integer (but the precedence takes care of that). Finally, we are writing beyond the string literal (but not beyond the bigger backing buffer). –  orion Mar 7 at 8:19
 
Doesn't seem too bad. I've only coded a little in C++, but I can figure this out. –  Navin yesterday
add comment

Java

enum derp
{

    public static void main(String[] a)
    {
        System.out.println(new org.yaml.snakeyaml.Yaml().dump(new java.awt.Point()));
    }
}

And how that one works:

Firs you think the Enum is not valid but its valid; then you think it will print a standard Point objects attributes but Gotcha! due to how Snakeyaml serializes you get a smooth StackOverFLow error

And another one:

enum derp
{

    ;public static void main(String[] a)
    {
        main(a);
    }
    static int x = 1;

    static
    {
        System.exit(x);
    }
}

you think a Stackoverflow will happen due to the obvious recursion but the program abuses the fact that when you run it the static{} block will be executed first and due to that it exits before the main() loads

enum derp
{

    ;
        public static void main(
            String[] a)
    {
        int aa=1;
        int ab=0x000d;
        //setting integer ab to \u000d  /*)
        ab=0;

        /*Error!*/
        aa/=ab;
    }
    static int x = 1;
}

this one relies on that /*Error*/-commented out code as closing point for the comment opened before the ab=0; the explain about the integer ab to 0x000d hides the newline to activate the commentout of the next line

share|improve this answer
1  
I can't right now, but it would be nice if you were to reformat this, if possible. It's a bit hard to read as is... :P –  Jwosty Mar 6 at 23:42
 
made em more obvious; and spoiler tags are intended cause the tricks arent obvious at first –  masterX244 Mar 6 at 23:56
 
Ah, much better :) –  Jwosty Mar 6 at 23:58
1  
Wait, so the first one does, in fact, produce an error? That's the opposite of what the question is asking. And why not just System.exit(1) in the second? –  Riking Mar 7 at 9:01
1  
No java programmer would expect an stack overflow in the second snippet. Sorry, that's by far too obvious. –  still_learning 2 days ago
show 3 more comments

C

main=195;

Works on x86 platforms, where 195 is the opcode for ret. Does nothing,

share|improve this answer
 
The opcode for ret is 195, not 193, right? –  Dennis yesterday
 
Doesn't work for me. I'd expect this to execute the code at address 195. –  nwellnhof yesterday
 
Tbanks @Dennis, the code was correct, the explanation wrong. –  ugoren yesterday
 
@nwellnhof, it only works on x86, and with compilers such as gcc which don't enforce the rules strictly. On what platform did you try it? –  ugoren yesterday
 
On any platform (including modern x86) where pages can be readable without also being executable, this will crash upon entry to main because main has been placed in the data segment, which is not executable. Amusingly, const int main=195 will not crash (on x86) (but will produce a garbage exit status) because .rodata by default is put in the same segment as .text and is therefore executable. (const char main[]="1\300\303"; will exit succesfully! (still on x86)) –  Zack 9 hours ago
show 1 more comment

python

 = 3

You expect

SyntaxError: unexpected indent

Instead you get

SyntaxError: invalid character in identifier

Also this:

" " == " "
False

Unicode spaces

share|improve this answer
 
I just tried this in python 2.7. The output is different from yours. = 3 -> SyntaxError: invalid syntax, " " == " " -> True –  Vader Mar 7 at 1:59
2  
@Vader: NO-BREAK SPACE (U+00A0) will be converted to SPACE (U+0020) on copy/paste under Windows. –  n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ Mar 7 at 2:03
 
@n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ that fixes the issue with the ==. The = 3 is still invalid syntax. I am not entirely sure what you are saying but I think you are trying to tell me that because I copied and pasted the = 3 I will not get the desired output. –  Vader Mar 7 at 2:07
 
@Vader: I have no idea about the first one. I only comment about the 2nd one. –  n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ Mar 7 at 2:15
5  
I don't expect SyntaxError: unexpected indent just sayin' –  gcq Mar 7 at 15:13
add comment

VBScript

function[:(](["):"]):[:(]=["):"]:
end function
msgbox getref(":(")(":)")

'Output: :)

What it does:

Function, Sub and Variable Names in VBScript can be anything if you use square brackets. This script makes a function called :( and one argument "):" but because they do not follow normal naming convention they are surrounded by square brackets. The return value is set to the parameter value. An additional semicolon is used to get everything on one line. The Msgbox statement get a reference to the functions (but does not need the brackets) and calls it with a smiley :) as parameter.

share|improve this answer
add comment

C++

Mixing trigraphs and space-less lambdas can be quite confusing and definitely look erroneous to people who are not aware of trigraphs:

int main()
{
    return??-??(??)()??<return"??/x00FF";??>()??(0??);
}

How it works:

Some sequences consisting of 3 symbols, beginning with ??, are called trigraphs and will be substituted by a fully-compliant preprocessor. Preprocessed, the line in question looks as follows: return ~[] (){ return "\x00FF"; }()[0]; As one can see, this is nothing but a superfluous lambda function returning a string consisting of the 0xFFth character. The [0] just extracts that character and ~ NOTs it, so 0 is returned.

share|improve this answer
3  
The valid C++ program int main(){(([](){})());} might also look nice when trigraphed... –  Angew Mar 7 at 15:29
add comment

First post here, I'm not sure I get this or not, but here goes.

<html>
    <head></head>
    <body>
        <?php $_POST['non-existant'] = $idontexisteither ?>
    </body>
</html>

It's a .html file...

share|improve this answer
4  
So the trick is just that it won't execute the PHP block because the file has .html extension and your web server is not configured to parse .html files as PHP? –  VisioN Mar 7 at 13:05
3  
Yes. Is this cheating? @VisioN –  BeatAlex Mar 7 at 13:53
 
I'm pretty sure this is cheating. At Least write "HTML" in bold at the top. –  Navin yesterday
add comment

Java

public class WhatTheHeckException extends RuntimeException {
    private static double d;        // Uninitialized variable
    public static void main(String... args) {
        if (d/d==d/d) throw new WhatTheHeckException();
        // Well that should always be true right? == is reflexive!

        System.out.println("Nothing to see here...");
    }
}

Why this works:

Unitialized fields have default values. In this case d is just 0. 0/0 = NaN in double division, and NaN never equals itself, so the if returns false. Note this would not work if you had 0/0==0/0, as at would be integer 0/0 division would WOULD throw an ArithmeticException.

share|improve this answer
add comment

Python

print """""quintuple-quoted strings!"""""

Perfectly valid, but the output is hard to guess. The first 3 " characters start a multiline string and the next two are part of the string. At the end, the first three "s terminate the string and the last two are an empty string literal that gets concatenated by the parser to the multiline string.

share|improve this answer
2  
Just a bonus: print """""""""Python strings don't have to start with the same number of quotes they end with.""""". –  xfix yesterday
add comment

Java (java.util.regex.Pattern)

This post's effectiveness depends on how much you know about Pattern class documentation. The behavior shown below also depends on the quirks in OpenJDK's Java Class Library (JCL) implementation of Pattern class.

  1. Inline flags (valid ones as shown in documentation (?idmsuxU-idmsuxU))

    Pattern.compile("(?t)"); // Throws PatternSyntaxException. Nothing surprising here
    
    Pattern.compile("(?c)"); // Compiles normally (!)
    

    c flag was intended to be used as inline flag for CANON_EQ, but it currently has absolutely no effect, due to the way CANON_EQ is handled.

    There is absolutely no reason to use this in your code.

  2. Character class intersection (shown in documentation as [\p{L}&&[^\p{Lu}]] or [a-z&&[def]], i.e. nesting seems to be required from the example)

    Pattern.compile("[\\p{IsAlphabetic}&&\\pM]"); // Compiled normally (!)
    

    And the compiled Pattern also works when matching against "\u0345".

    However, it is still recommended that you follow the documentation's way of writing regex.

  3. Character class in \p notation (shown in documentation to specify a POSIX character class, a java.lang.Character class, or for Unicode script/block/category/binary property)

    Pattern.compile("\\p{Letter}"); // Throws PatternSyntaxException. Nothing surprising here
    
    Pattern.compile("\\p{all}"); // Both compiles normally (!)
    Pattern.compile("\\p{L1}");
    

    all and L1 are hidden names usable by \p:

    • \p{all} is equivalent to (?s:.).
    • \p{L1} is equivalent to [\x00-\xFF].

    However, since this is not specified in the documentation, I strongly advise you against using them even if you know you can use them.

share|improve this answer
add comment

C++

How many times have you been told to be careful to avoid index out of bounds errors with your for loops?

#include<iostream>
#include<string>
using namespace std;

int main() {
    string s="text here";
    for(int i=0;i<=s.size();i++)
        cout<<s[i];
    return 0;
}

In C++ (and most other languages), strings are just special char-arrays. In C++, a string always has a buffer of a space at the end, which isn't usually noticed because all the functions, etc. account for it. Here I am just accessing the space directly, so it just prints a space instead of crashing with and index out of bounds error.

share|improve this answer
 
Well, that's rather obvious. Indeed, operator[] doesn't check bounds, unlike at() method. Even if there were no buffer of spaces, you'd not get any error (although it really looks like a UB). –  Ruslan Mar 7 at 9:31
 
@Ruslan If I do i<=s.size()+1;, I get an index out of bounds (it compiles, but crashes). Also, if I reference a vector or array this way, it crashes. With those, I have to use the < operator instead. –  hosch250 Mar 7 at 16:31
3  
Ah, I guess why it doesn't crash here. It's not a buffer of space — it's a zero terminator. That's why it works so only for std::string and only for one single character above maximum. Also, you can't get an exception for operator[] because it doesn't check bounds. You can only get a segfault on "real" out of bounds problem (e.g. with an address sanitizer). –  Ruslan Mar 7 at 20:13
add comment

PHP

Some slightly non-standard syntax here:

<html>
<body>
<p>Error?</p>
<?php 

echo beach, far away in time;

?>
<p>What error??</p>

What's going on?

There's a three-per-em space after the opening <?php tag. The PHP parser treats this as part of the tag name, and therefore fails to recognise this code block as PHP. Instead it passes it straight to your web browser. Your browser doesn't understand it either, so all you see is the HTML text that surrounds it. (An ordinary non-breaking space would have worked too, but Markdown converts those to regular spaces so we need to use something different.)

share|improve this answer
add comment

VBScript

Visual Basic 6 users will know that

If Blah Then Foo Bar

is legal, as is

If Blah Then 
    Foo Bar
End If

But what about

If Blah Then Foo Bar End If

? Turns out that is legal in VBScript but not in VB6. Why?

It's a bug in the parser; the intention was to reject this. The code which detects the End If was supposed to also check whether it was a multi-line If statement, and it did not. When I tried to fix it and sent out a beta with the fix, a certain influential industry news organization discovered that they had this line of code in one of their VBScript programs and said they would give the new version a low rating unless we un-fixed the bug, because they didn't want to change their source code.

share|improve this answer
 
Is there any disadvantage to leaving the bug un-fixed, aside from allowing you to write VBS code that isn't valid in VB6? –  Gabe 2 days ago
 
@Gabe: No, there's no downside other than it being harder to port VBScript code to VB. –  Eric Lippert 2 days ago
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.