text:
Which Numbers Would Crash this Function?
Which values of x and y will cause a crash with some C compilers?
int f(int x, int y) {
    return (y==0) ? 0 : (x/y);
}

Since C's ternary operator shortcuts, I would say none would.  This question doesn't seem to fit the format for this site, which is focused on program puzzles and code golf.  See the faq for details http://codegolf.stackexchange.com/faq.

This isn't code golf, but is a puzzle. There is an answer, and it's just a couple of numbers.

I stand corrected.

Actually, judging by the K&R book, this function really must never crash. But by the ANSI C standard, the behavior in the particular crashing case is undefined, and with x86 compilers it crashes.

Does undefined mean that it doesn't crash?  Or does it mean that it's the implementations choice how to handle such things?  Does the C standard preclude signed integers from being represented by ones' complement?

Undefined means it's implementation dependent, and may return any value, crash, or format your hard disk. The C standard says that if the result of division can't be stored in an integer (which is the case here), behavior is undefined.

The FAQ is quite clear that puzzle on this site are expected to have an objective criteria for determining a winner. A "give me a list of examples" type problem does not qualify because all examples are equally valid.

@dmckee, If you give the right answer, you're the winner. What cretirion could be more clear and objective? There's only one answer (or do you have another example?)

-2147483648 (INT_MIN) and -1
#include <stdio.h>
#include <limits.h>
int f(int x, int y) {
    return (y==0) ? 0 : (x/y);
}
int main() {
    int r = f(INT_MIN, -1);
    printf("%d\n", r);
    return 0;
}

$ gcc -Wall division.c && ./a.out # => zsh: floating point exception  ./a.out

Indeed. Though this should give a warning, because 2147483648 isn't a valid integer.

Yes, that's why I used INT_MIN after, to use a valid int. I guess the reason is 2147483648 is not a valid int, since INT_MAX is 2^31-1 with 32-bit int.

Ah.  Two's complement.  I missed that.

Yes, it should compile cleanly with INT_MIN (which is -2147483648).

The right answer is already given, but I immediately thought about Microsoft Pex.

Pex automatically generates test suites with high code coverage. Right
  from the Visual Studio code editor, Pex finds interesting input-output
  values of your methods, which you can save as a small test suite with
  high code coverage. Microsoft Pex is a Visual Studio add-in for
  testing .NET Framework applications

After adding your puzzle in the sandbox site, it finds the answer in a few seconds, the same as eregons answer. (click ask pex)
Note: it does it in C#, but the language is not really relevant.

x: int.MinValue
y: -1
Exception: OverflowException
Message:
Arithmetic operation resulted in an overflow.

Nice. It surely doesn't brute-force it, because it wouldn't end in a few seconds. I guess someone in MS realized that numbers around 0 and MAX_INT are always interesting.

Hopefully it's a little more clever than that. It might look at (x/y) and know that INT_MIN, -1, 0 etc. are all problem cases for that expression, and try to reverse engineer a way to produce those values at the time of evaluation.


text:
Shortest route through a one-way system
My home town, Rhyl, has a one-way traffic system which seems to have been designed to keep people away from their destination for as long as possible. Your task, should you choose to attempt it, is to produce a program to give the shortest route through such a traffic system.
Input
Input will be on STDIN, and will be a list of start and end points followed by a blank line followed by a list of queries, as follows:
A B
B A
B C
C D
D C

A D
C A
B A

Each road can only be travelled in the direction(s) given, so, in the above example the road A - B is a two way street whereas B - C is a one-way street from B to C. Travelling from C to B is prohibited.
Start and end points will all be represented by a single upper-case letter.
Output
Output should be the shortest route (measured by number of points visited) from the given start point to the given end point for each query received. If no such route exists, output a blank line. If more than one shortest route exists, output the first when sorting all shortest routes lexicographically.
For the above example the output would be:
A B C D

B A

Test Scripts
As before I'm providing tests for this task based on scripts written by Joey and Ventero:-

Bash
PowerShell

and also tests and expected output for anyone who can't use the above scripts

Plain text

Usage: ./test [your program and its arguments]
Rewards
All answers which have obviously had some attempt at golfing that meet the spec and pass all the tests will get my upvote. The shortest working answer by 26/01/2012 will be accepted.

output the first when sorting all shortest routes lexicographically - So if A B D and A C D are both valid solutions, output A B D instead?

@GigaWatt Yes, that's right.

This is awfully close to a duplicate of http://codegolf.stackexchange.com/questions/3474/choose-your-own-adventure

@PeterTaylor Why didn't you raise that while it was in the question sandbox? What do you suggest? I could delete it while there are no answers on it, I suppose?

@Gareth, because for once there was activity on a few threads on meta at the same time, and I didn't notice that there was a new reply in the question sandbox. Deletion is one possibility; or you could extend it to weight the edges - we haven't had a directed Dijkstra question yet.

@PeterTaylor Fair enough. A rewrite to weight the edges would take a fair amount of time though, especially re-doing the tests.

D'oh! I forgot that one when I was looking for similar questions. Sorry, GigaWatt. There is none-the less a small difference that arises from the shortes path and lexical sorting conditions. I think it can stay, though as @Peter says weighting is always fun.

@dmckee Ok, I'll leave it as it is and accept that people may ignore it as a duplicate. I'll come up with a weighted graph question next time if no-one beats me to it.

test cases seem to have problem, in testcase#2, J->A->I is a path, while you marked "J B I" as the answer.

@Gajet Okay, fixed it. Doing it by hand is no match for getting a program to do it for you. :-)

Haskell, 223 207 characters
main=interact$unlines.f.break null.map words.lines
s%[f,t]=[[f]]#t where[]#_="";x#t|y@(_:_)<-[z|z<-x,last z==t]=unwords$minimum y|1<3=s&x#t
s&z=[x++[b]|x<-z,[a,b]<-s,last x==a,notElem b x];f(s,_:q)=map(s%)q

Python (2.x), 382 369 358 338 323 318 characters
All tips and comments welcome!
import os;u=str.split;l=u(os.read(0,1e9),'\n')
p,g,c=l.index(''),{},map;o=g.setdefault
def f(g,s,e,q=[]):q=q+[s];y=([],[q])[s==e];[c(y.append,f(g,n,e,q))for n in set(o(s,[]))-set(q)];return y
for k,v in c(u,l[:p]):o(k,[]);g[k]+=v
for w,e in c(u,l[p+1:]):h=sorted(f(g,w,e));print''if not h else' '.join(min(h,key=len))

Should pass the tests in this form. Feed input via stdin, e.g. python shortestroute.py < test.txt.

Seems to fail query 2 of test 4. Returns A B I J M instead of A B G J M.

@Gareth: there was indeed a small bug considering lexographical sort of similar length solutions, should be fixed now...

C:450,437,404,390 characters
#include<stdio.h>
#include <string.h>
r[99][99],p[99],q[99],m[99],i,j,x,y,s;
char t[9],e[9999];
F(k)
{
    m[k]^s?r[p[k]=q[i]][k]?m[q[j++]=k]=s:0:0;
    if(++k<99)F(k);
}
f()
{
    F(0);
    if(++i^j)f();
}
P(o)
{
    if(p[o])P(p[o]);
    *t=m[o]^s?0:o;
    strcat(e,t);
}
w()
{
    gets(t);
    r[*t][t[2]]=*t?w():0;
}
W()
{
    gets(t);
    x=*t,x?y=t[j=2],s=x+y*99,m[q[t[2]=i=p[x]=0]=x]=s,f(),P(y),strcat(e,"\n"),W():0;
}
main()
{
    w();
    W();
    puts(e);
}

puts("\n") prints two newlines.  puts() automatically adds an end-of-line terminator to the strings it prints.  To avoid that behavior, use fputs(str, stdout) or simply printf(str).

Bends the rules slightly - should take all the input in one go and then output all the answers to the queries in one go. I'll +1 it because it works fine (and found mistakes in the tests), but I won't be able to accept it over a longer program that fully complies with the input/output requirements.

@Gareth: fixed. though, answer output should not be as longer than 9999 characters!

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Convert from Infix Notation to Prefix Notation
Given an arithmetic expression, which can include parentheses (()), exponents (^), division (/) and multiplication (*), addition (+) and subtraction (-) (in that order of operation), such as
a ^ (2 / 3) * 9 * 3 - 4 * 6

output the same expression in prefix notation.
(- (* (* (^ a (/ 2 3)) 9) 3) (* 4 6))

Spaces are optional in the input as well as the output. You may assume that all operators are left-associative and that all of the numbers in the expression are single digit integers (i.e. [0-9]).
This is a code golf challenge, so the shortest solution wins.

Are + and - the same precedence, or is + higher than -?  I.e., is 3+4-5+6 = (((3+4)-5)+6) or ((3+4)-(5+6))?

Also, you left out division in your list of operations.

are parentheses optional in output?

@KeithRandall * and / have the same precedence, as do + amd -.

@Gajet No, they're not.

Ruby 1.9 - 134
%w[** / * + -].map{|o|String.send(:define_method,o){|n|"(#{o=='**'??^:o} #{self} #{n})"}}
puts eval gets.gsub(/\w/,'?\0').gsub ?^,'**'

Pretty evil, but it works:
$ echo 'a ^ (2 / 3) * 9 * 3 - 4 * 6' | ruby sol.rb
(- (* (* (^ a (/ 2 3)) 9) 3) (* 4 6))

Python, 222 chars
class A:
 def __init__(s,x):s.v=x
for x in('pow^','mul*','div/','add+','sub-'):exec('A.__'+x[:3]+'__=lambda s,y:A("('+x[3]+'"+s.v+y.v+")")')
import re
print eval(re.sub('(\\w)','A("\\1")',raw_input().replace('^','**'))).v

Similar to the Ruby one, except Python doesn't let you redefine the global ops, only ops of a class.

Perl 6 (146|150)
The easiest way to do this is to just swap out the subroutines that implement the operators for new ones.
sub infix:«+»   ($a,$b) { "(+ $a $b)" }
sub infix:«-»   ($a,$b) { "(- $a $b)" }
sub infix:«*»   ($a,$b) { "(* $a $b)" }
sub infix:['/'] ($a,$b) { "(/ $a $b)" } # stupid highlighter
sub infix:«**»  ($a,$b) { "(^ $a $b)" }

# currently there seems to be a bug that
# prevents this from modifying the parser correctly
# probably because there is already a different operator with this name
# which has nothing to do with exponentiation
my &infix:«^» := &[**];

say 'a' ** (2 / 3) * 9 * 3 - 4 * 6;
# (- (* (* (^ a (/ 2 3)) 9) 3) (* 4 6))␤

The absolute minimum amount of bytes for doing it this way is:
sub infix:<+>{"(+ $^a $^b)"}␤  #   29
sub infix:<->{"(- $^a $^b)"}␤  # + 29
sub infix:<*>{"(* $^a $^b)"}␤  # + 29
sub infix:<**>{"(^ $^a $^b)"}␤ # + 30
sub infix:</>{"(/ $^a $^b)"}␤  # + 29

146 bytes, although it makes more sense to count graphemes in Perl 6.
This assumes that "output the same expression in prefix notation" could just refer to the result of the expression, not necessarily the output of the program.
You would have to add say  in front of the expression to get the program to print it to STDOUT. (150 bytes)

Unix TMG, 189 bytes
p:ignore(<< >>)parse(e);e:q(t,a);t:q(x,m);x:q(r,h);q:proc(x,y)x k:y/d x={<(>2 3 1<)>}b\k;r:o(!<<+-*/^()>>)|<(>e<)>;a:o(<<+->>);m:o(<<*/>>);h:o(<<^>>);o:proc(n)smark any(n)scopy;d:;b:bundle;

The solution is almost straight from the manual for the language, with only basic golfing.
Expanded:
prog:  ignore(<< >>) parse(expr);
expr:  q(term, addop);
term:  q(fact, mulop);
fact:  q(prim, expop);
q:     proc(x,y) x k: y/done x ={ <(> 2 3 1 <)> } b\k;
prim:  op(!<<+-*/^()>>) | <(> expr <)>;
addop: op(<<+->>);
mulop: op(<<*/>>);
expop: op(<<^>>);
op:    proc(n) smark any(n) scopy;
done:  ;
b:     bundle;

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Finding Not-Quite-Prime Numbers
Your challenge, should you chose to accept it, is to code-golf a function that returns true or false (or some similar meaningful representation of yes and no) if a number meets the following criteria:

The integer itself is a prime number OR
Either of its neighbor integers are prime

For example:
An input of 7 would return True.
An input of 8 would also return True.
An input of 15 would return False.  (Neither 14, 15, or 16 are prime)
The input must be able to return correctly for numbers between 2^0 and 2^20 inclusive, so there's no need to worry about sign issues or integer overflows.

32-bit number overflows, not buffer overflows, I guess.

Whoops, meant "integer overflow".  Brain went on autopilot.

J, 17
*/<:$&q:(<:,],>:)

Returns booleans encoded as process return codes: zero for true, nonzero for false.  Sample use:
   */<:$&q:(<:,],>:) 7
0
   */<:$&q:(<:,],>:) 8
0
   */<:$&q:(<:,],>:) 15
3

*/0 p:<:,],>: is shorter and a proper (lambda) function is ([:*/0 p:<:,],>:)

Haskell, 47 characters
f n=any(\k->all((>0).mod k)[2..k-1])[n-1..n+1]

Python 85 80
def f(n):g=lambda n:all(n%i!=0for i in range(2,n));return g(n)or g(n-1)or g(n+1)

First time on Code Golf so there's probably some tricks I'm missing.

You can remove the []. all will be more than happy to work with a generator expression. If you don't mind your code being ugly, you can also remove the spaces between 0 and for, and ) and or.

@stranac Awesome. Thank you very much.

Made a few straightforward changes, hopefully it still works: f=lambda n:any(all(m%i for i in range(2,m))for m in[n,n-1,n+1])

@Nabb Very nice. Well done.

Not a real contender in code shortness by any means, but still submitting since determining primeness by regular expression is twisted in many ways!
Python (2.x), 85 characters
import re
f=lambda n:any(not re.match(r"^1?$|^(11+?)\1+$","1"*x)for x in[n,n-1,n+1])

You can remove the for loop and build it into the regexp by testing "1"*(n+1) but starting with ^1?1? instead.

Ruby (55, or 50 as lambda)
def f q;(q-1..q+1).any?{|n|(2..n-1).all?{|d|n%d>0}};end

or as lambda (use g[23] to call it)
g=->q{(q-1..q+1).any?{|n|(2..n-1).all?{|d|n%d>0}}}

Coffeescript (53)
p=(q)->[q-1..q+1].some (n)->[2..n-1].every (d)->n%d>0

 It should be "proc" not "lambda" ;-)

The boring Mathematica, 35 solution!
PrimeQ[n-1]||PrimeQ[n]||PrimeQ[n+1]

At least you may golf it into Or@@PrimeQ/@{n-1,n,n+1}.

This is not a function.

@MartinBüttner: I don’t know Mathematica, sorry.

Using Howard's version, Or@@PrimeQ@{#-1,#,#+1}& (the slash in his code isn't needed)

C, 112 82 72 characters
Following Ilmari Karonen's comment, saved 30 chars by removing main, now P returns true/false. Also replaced loop with recursion, and some more tweaks.
p(n,q){return++q==n||n%q&&p(n,q);}P(n){return p(-~n,1)|p(n,1)|p(~-n,1);}

Original version:
p(n,q,r){for(r=0,q=2;q<n;)r|=!(n%q++);return!r;}
main(int n,int**m){putchar(48|p(n=atoi(*++m))|p(n-1)|p(n+1));}

You could save 2 chars with main(n,m)int**m;.

...and besides, the challenge says "code-golf a function".

Mathematica, 24 bytes
Don't know why this old post showed up in my list today, but I realized Mathematica is competitive here.
Or@@PrimeQ/@{#-1,#,#+1}&

Unnamed function taking an integer argument and returning True or False. Direct implementation.

PrimeQ threads over lists, so Or@@PrimeQ@{#-1,#,#+1}& (or Or@@PrimeQ[#+{-1,0,1}]&) also works, for -1 byte. (Although, I guess I don't know if PrimeQ threaded over lists in 2012.)

Stax, 6 bytes
Ç▀<╝ºΩ

Run and debug it
Explanation (unpacked):
;v:Pv<! Full program, implicit input  Example: 7
;v      Copy input and decrement               7 6
  :P    Next prime                             7 7
    v   Decrement                              7 6
     <! Check if input is >= result            1

JavaScript (71 73 80)
n=prompt(r=0);for(j=n-2;p=j++<=n;r|=p)for(i=1;++i<j;)p=j%i?p:0;alert(r)

Demo: http://jsfiddle.net/ydsxJ/3/
Edit 1: Change for(i=2;i<j;i++) to  for(i=1;++i<j;) (thanks @minitech).  Convert if statement to ternary.  Moved r|=p and p=1 into outer for to eliminate inner braces. Saved 7 characters.
Edit 2: Combine p=1 and j++<=n to p=j++<=n, save 2 chars (thanks @ugoren).

You can use for(i=1;++i<j;) instead of for(i=2;i<j;i++) to save 1 more character.

@minitech: !j%i won't work because of precedence. A working alternative is j%i<1.

@Nabb: Wow, you're right. That's silly.

How about p=j++<=n? If Javascript is like C here, it should work.

@ugoren: Looks like it worked, thanks!

Regex (ECMAScript), 20 bytes
^x?x?(?!(x+)(x\1)+$)
Try it online!
The above version does not correctly handle zero, but that only takes 1 extra byte:
^x?x?(?!(x+)(x\1)+$)x
As an added bonus, here's a version that gives a return match of 1 for one less than a prime, 2 for prime, and 3 for one more than a prime:
^x?x??(?!(x+)(x\1)+$)x
Try it online!

The range the question speaks about it is "between 2^0 and 2^20" so 1..2^20 so 0 there isn't...

@RosLuP Which is exactly why my primary answer is 20 bytes and doesn't handle 0 correctly. I find value in going beyond the precise specifications of the question and giving more robust answers, along with the answer that minimally matches the question's spec.

Sometimes I do the same (write 'unnecessary' test) but this seems goes against codegolf way of thinking, and people that write them are not considered "serious"...

@RosLuP But what's the harm, as long as I give the minimal answer as my primary answer? And can you give any examples of people who actually think that way? I could understand it if I gave my only answer as the robust one, but I'm not doing that.

C#, 96
It returns -1,0,1 for true, anything else is false.
Any suggestions to make it shorter would be wonderful!
int p(int q){var r=q-1;for(var i=2;i<r&r<q+2;i++){if(i==r-1)break;if(r%i==0)r+=i=1;}return r-q;}

Expanded form:
int p(int q){
    var r=q-1;
    for(var i=2;i<r&r<q+2;i++){
        if(i==r-1)break;
        if(r%i==0)r+=i=1;
    }
    return r-q;
}

I'm not entirely sure, but I think you could remove the if(i==r-1)break; and change the middle of the for loop from i<r to i<r-1. It would bring you down to 82.

GolfScript: 26
)0\{.:i,{i\%!},,2=@|\(}3*;

Explanation:
    The innermost block {.:i,{i\%!},,2=@|\(} determines if the top of the stack is prime by checking if there are exactly 2 factors less than the top of the stack.  It then disjuncts this with the second item on the stack, which holds the state of whether a prime has been seen yet.  Finally, it decrements the number on the top of the stack.
Start by incrementing the input, initializing the prime-seen state, and repeat the block 3 times.  Since this will decrement twice, but we started by incrementing, this will cover n+1 and n-1.

C#, 87 97 chars
bool p(int q){return new[]{q-1,q,q+1}.Any(x=>Enumerable.Range(2,Math.Abs(x-2)).All(y=>x%y!=0));}

I don't think this works with 1 or 2 as input

@BenReich It didn't. I had to add ten chars to fix it :(

CJam, 12 bytes
CJam is much younger than this challenge, so this answer is not eligible for the green checkmark (which should be updated to randomra's answer anyway). However, golfing this was actually quite fun - I started at 17 bytes and then changed my approach completely three times, saving one or two bytes each time.
{(3,f+:mp:|}

This is a block, the closest equivalent to a function in CJam, which expects the input on the stack, and leaves a 1 (truthy) or 0 (falsy) on the stack.
Test it here.
Here is how it works:
(3,f+:mp:|
(          "Decrement the input N.";
 3,        "Push an array [0 1 2].";
   f+      "Add each of those to N-1, to get [N-1 N N+1].";
     :mp   "Test each each element for primality, yielding 0 or 1.";
        :| "Fold bitwise OR onto the list, which gives 1 if any of them was 1.";

F#, 68 bytes
let p n=Seq.forall(fun x->n%x>0){2..n-1}
let m n=p(n-1)||p n||p(n+1)

Try it online!
This is why I love code golf. I'm still very green with F# but I learn so much about how the language works and what it can do from these kinds of challenges.

Why is it non-competing?

Because I'm not sure if I'm using anything in F# today that wasn't around when the question was asked in 2012. I admit it's pedantic - even paranoid. But I write pharmaceutical software for a living. Paranoia is healthy. ;)

Look at F#'s version table in Wikipedia. Depending on the version you need, it may be older than the question.

APL (Dyalog Classic), 20 bytes
0∊¯1 0 1∘+∊(∘.×⍨1↓⍳)

Try it online!

Retina, 22 bytes
$
1
^1?1?(?!(11+)\1+$)

Try it online!
Takes unary as input

A pure regex Retina solution beats this by 2 bytes.

Looks like this was what Howard had in mind.

Java 8, 83 bytes
n->n==1|p(n-1)+p(n)+p(n+1)>0int p(int n){for(int i=2;i<n;n=n%i++<1?0:n);return--n;}

Returns true / false as truthy/falsey values.
Try it online.
Explanation:"
n->                    // Method with integer parameter and boolean return-type
  n==1                 //  Return whether the input is 1 (edge-case)
  |p(n-1)+p(n)+p(n+1)>0//  Or if the sum of `n-1`, `n`, and `n+1` in method `p(n)` is not 0

int p(int n){          // Separated method with integer as both parameter and return-type
  for(int i=2;i<n;     //  Loop `i` in the range [2, `n`)
    n=n%i++<1?         //   If `n` is divisible by `i`
       0               //    Change `n` to 0
      :                //   Else:
       n);             //    Leave `n` as is
                       //  (After the loop `n` is either 0, 1, or unchanged,
                       //   if it's unchanged it's a prime, otherwise not)
  return--n;}          //  Return `n` minus 1

So int p(int n) will result in -1 for n=0 and non-primes, and will result in n-1 for n=1 or primes. Since p(0)+p(1)+p(2) will become -1+0+1 = 0 and would return false (even though 2 is a prime), the n=1 is an edge case using this approach.

A single loop without separated method would be 85 bytes:
n->{int f=0,j=2,i,t;for(;j-->-1;f=t>1?1:f)for(t=n+j,i=2;i<t;t=t%i++<1?0:t);return f;}

Returns 1 / 0 as truthy/falsey values.
Try it online.
Explanation:
n->{              // Method with integer as both parameter and return-type
  int f=0,        //  Result-integer, starting at 0 (false)
      j=2,i,      //  Index integers
      t;          //  Temp integer
  for(;j-->-1;    //  Loop `j` downwards in range (2, -1]
      f=          //    After every iteration: Change `f` to:
        t>1?      //     If `t` is larger than 1 (`t` is a prime):
         1        //      Change `f` to 1 (true)
        :         //     Else:
         f)       //      Leave `f` the same
    for(t=n+j,    //   Set `t` to `n+j`
        i=2;i<t;  //   Inner loop `i` in the range [2, t)
      t=t%i++<1?  //    If `t` is divisible by `i`:
         0        //     Change `t` to 0
        :         //    Else:
         t);      //     Leave `t` the same
                  //   (If `t` is still the same after this inner loop, it's a prime;
                  //   if it's 0 or 1 instead, it's not a prime)
  return f;}      //  Return the result-integer (either 1/0 for true/false respectively)

Japt, 7 bytes
´Uô2 dj
´Uô2    // Given the range [U-1..U+1],
     dj // sing "Daddy DJ", uh, I mean, check if any are a prime.

Try it online!

Jelly, 5 bytes
‘r’ẒẸ

Try it online!
How it works
‘r’ẒẸ    Monadic main link. Input: integer n
‘r’      Generate range n-1..n+1
   ẒẸ    Is any of them a prime?

C++
k=3;cin>>i;i--;
while(k)
{l[k]=0;
  for(j=2;j<i;j++)
   if(!(i%j))
     l[k]++;
  k--;
  i++;
}
if(!l[1]|!l[2]|!l[3])
     cout<<"1";
else cout<<"0";

Welcome to CodeGold.SE. If you look at the other answers you'll notice a common format used for answers to [code-golf] questions. You might want to apply it to your answers as well.

Q, 43 chars 36
{any min each a mod 2_'til each a:x+-1 0 1}
{any(min')a mod 2_'(til')a:x+-1 0 1}

R, 68 chars
f=function(n){library(gmp);i=isprime;ifelse(i(n-1)|i(n)|i(n+1),1,0)}

Usage (1 for TRUE, 0 for FALSE):
f(7)
[1] 1
f(8)
[1] 1
f(15)
[1] 0

I don’t really know how R works, but could you just do i(n-1)|i(n)|i(n+1) instead of ifelse(i(n-1)|i(n)|i(n+1),1,0)?

You are right: g=function(n){library(gmp);i=isprime;i(n-1)|i(n)|i(n+1)} - down to 56 characters! ;-)

J, 16 chars
   (_2&<@-4 p:]-2:)

   (_2&<@-4 p:]-2:) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
1 1 1 1 1 1 1 1 0 1 1 1 1 1 0 1 1 1 1

Python, 69 67 chars
any(all(i%j for j in range(2,i))for i in range(input()-1,8**7)[:3])

8**7 > 2**20 while being slightly shorter to write

Ruby, 47 chars but very readable
require'Prime'
f=->x{[x-1,x,x+1].any? &:prime?}

C++ 97
ugoren seems to have beat me to the clever solution. So he's a shortish version on the loop three times approach:
P(int k){int j=1;for(int i=2;i<k;){j=k%i++&&j;}return j;}
a(int b){return P(b)|P(b+1)|P(b-1);}

Forth (gforth), 104 bytes
: p dup 1 > if 1 over 2 ?do over i mod 0> * loop else 0 then nip ;
: f dup 1- p over 1+ p rot p + + 0< ;

Try it online!
Explanation
Prime check (p)
dup 1 > if          \ if number to check if greater than 1
   1 over 2 ?do     \ place a 1 on the stack to act as a boolean and loop from 2 to n
      over i  mod   \ take the modulo of n and i
      0> *          \ check if greater than 0 (not a divisor) and multiply result by boolean
   loop             \ end the loop, result will be -1 if no divisor was found (prime)
else                \ if n is less than 2
   0                \ put 0 on the stack (not prime)
then                \ end the loop
nip                 \ drop n from the stack

Main Function (f)
dup 1- p             \ get n-1 and check if prime
over 1+ p            \ get n+1 and check if prime
rot p                \ rotate stack to put n on top and check if prime
+ + 0<               \ add the three results and check if less than 0 (at least 1 was prime)

Julia 0.4, 23 bytes
n->any(isprime,n-1:n+1)

Try it online!

APL(NARS) 13 chars, 26 bytes
{∨/0π⍵+¯1..1}

Here {0π⍵} is the function says if its argument it is a prime
(return 1[true], else it return 0[false]), that function can have argument both one scalar integer or one list of integers as the above case... test:
  f←{∨/0π⍵+¯1..1}
  f¨1 2 7 8 14 15 16 (2*20)
1 1 1 1 1 0 1 0

authors: Gareth Heyes ล้้้้้้้้้้้้้้้้


text:
The Sleigh Packing problem
Santa's elves need help in determining if their current batch of presents will fit into santa's sleigh. Write the shortest program possible in the language of your choice to help them out.
Constraints

Santa's sleigh measures 6ft wide by 12ft long and is 4ft deep.
Presents may be fragile, so they may not be stacked on top of each other.
You can rotate and flip the presents as you wish, but Santa's quite an obsessive-compulsive chap so keep the rotations to multiples of 90 degrees.
North Pole health and safety regulations stipulate that presents may not stick out more than 1ft above the top of a sleigh (therefore they may not be more than 5ft high).

Input
Input will be on STDIN and will be one integer representing the number of presents in the batch followed by a list of the presents' dimensions - 1 present per line, 3 dimensions (in feet) separated by spaces.
Examples:
1
6 12 5

6
1 12 3
1 12 4
1 12 1
1 12 5
1 12 3
1 12 5

1
4 3 13

1
6 12 6

Output
Output should just be the word 'YES' if the presents can be packed into the sleigh or 'NO' if they cannot.
Output for the above examples:
YES

YES

NO

NO

Test scripts
As before, I've appropriated some test scripts written by Joey and Ventero to create some tests for this task:-

Bash
PowerShell

Usage: ./test [your program and its arguments]
Rewards
Each entry which I can verify that meets the spec, passes the tests and has obviously had some attempt at golfing will receive an upvote from me (so please provide usage instructions with your answer). The shortest solution by the end of the 2011 will be accepted as the winner.

Are we allowed to rotate the presents?  Flip them on their side?  Rotate them by an angle that's not a multiple of 90°?

@IlmariKaronen Yes, you can rotate the presents to any orientation you wish as long as they fit. I think the the maths involved in fitting boxes in at an angle that's not a multiple of 90 would be over-complicated wouldn't it? I've assumed only rotations of 90 degrees for the tests.

@IlmariKaronen Upon further thought, I think I need to eliminate rotations other multiples of 90 degrees to avoid over-complicating the question, and to ensure that the tests give correct answers. I'll add an extra constraint.

Why is example 3 a no when example 1 is a yes? 6x12x5 is bigger than 6x12x4 so are present allowed to poke out the top? In which case why is 3 a no as that too can stick out the top?

@Skizz: It's confusingly phrased, but see the fourth constraint: presents may stick 1ft out the top.  So the effective depth of the sleigh is 5ft, not 4ft.

Two bugs in the bash test script.  Test10 is packable (1 12 3 taking up a 1x12 spot on the floor, 3 4 1 and 4 7 1 taking up together a 1x10 spot, and 2 6 5 taking up a 2x6 spot, which easily fits) and test16 says it has 73 blocks, but it in fact has only 72 listed.

@KeithRandall Thanks, I've fixed both sets of tests.

Haskell, 312 318 chars
import Data.List
s(ξ:υ:_,λ:σ:η:_)(x:y:_,l:w:_)=(ξ+λ<=x||ξ>=x+l||υ+σ<=y||υ>=y+w)&&ξ+λ<7&&υ+σ<13&&η<6
y p l=[(v,r):l|v<-[[x,y,0]|x<-[0..5],y<-[0..11]],r<-permutations p,all(s(v,r))l]
main=do
 n<-readLn
 p<-mapM(fmap(map read.words).const getLine)[1..n]
 putStr.r$foldr((=<<).y)[[([9,0],[0..])]]p
r[]="NO"
r _="YES"

For some reason that I don't fully understand at the moment, it doesn't finish your tests #9 and #16 in reasonable time. But you didn't say anything about performance, did you?

373 383 chars
This version runs much faster for the examples: it first checks if it's not impossible simply because the area is too small, and then it starts with the largest parcels rather then inserting them in the given order. Note that the area detection is not perfect: it doesn't consider rotations, so it may on some inputs give wrong results. But it does work with the test script.
import Data.List
s(ξ:υ:_,λ:σ:η:_)(x:y:_,l:w:_)=(ξ+λ<=x||ξ>=x+l||υ+σ<=y||υ>=y+w)&&ξ+λ<7&&υ+σ<13&&η<6
y p l=[(v,r):l|v<-[[x,y,0]|x<-[0..5],y<-[0..11]],r<-permutations p,all(s(v,r))l]
π=product
main=do
 n<-readLn
 p<-mapM(fmap(map read.words).const getLine)[1..n]
 putStr$if sum(map(π.init)p)>72||null(foldr((=<<).y)[[([9,0],[0..])]].sortBy((.π).compare.π)$p)then"NO"else"YES"

No, I wasn't concerned with performance, but the program does have to pass all the tests to get my upvote. It's currently working on test 9. I'll leave it awhile to see if it finishes.

@Gareth I shall have to optimize it yet a bit.

Ok. It's still working on test 9 here.

Python, 461 chars
import sys
def L(P,z):
 if not P:return 1
 for w,h in[P[0],P[0][::-1]]:
  m=sum((2**w-1)<<i*6for i in range(h))
  for x in range(7-w):
   for y in range(13-h):
    n=m<<y*6+x
    if z&n==0and L(P[1:],z|n):return 1
 return 0
for G in sys.stdin.read().split('\n\n'):
 S=[(x,y)if z<6 else(x,z)if y<6 else(y,z)if x<6 else(9,9)for x,y,z in[sorted(eval(g.replace(' ',',')))for g in G.split('\n')[1:]if g]]
 print'YES\n'if sum(x*y for x,y in S)<73and L(S,0)else'NO\n'

L recursively checks if the rectangles in P can be put in the sleigh, where z is a bitmask of cells that are already occupied.  The S assignment determines which way is up for each of the packages (largest dimension <= 5 goes vertically).
The code is potentially exponential, but it is quick on all the test inputs.

GolfScript, 130 characters
"NO":g;~](;3/127{128*64+}12*\{.,0>.!{"YES":g;}*{([{[~@]..[~\]\}3*;]{)6<{~[2\?(]*128base 83,{2\?1$*.4$&0={3$|2$f}*}%;}*}%;}*;;}:f~g

It took quite some time to get it running in GolfScript. Any attempt to golf it further broke some of the test cases.
Please be warned that this version may become incredibly slow if you run it with too many presents.

I always have trouble with golfscript ones. I'm trying ./test ruby golfscript.rb howard.gs but it's giving me  errors. How should I be invoking it?

@Gareth You might just prepend semicolon followed by the input (e.g. ;"1\n6 12 5") to the given script.

Wow, you weren't kidding about it being slow on some cases. I may have to leave it all night on the two last test cases (72 and 73 presents respectively ;-)

Sorry, it won't go past test 5 in the test script. I can't upvote until it passes all the tests.

@Gareth Well, then this one won't get an upvote from your side ;-) It implements the full exponential approach in order to be short. I am working on a faster algorithm but it is not yet ready for submission. It needs considerably more space already and I still have some cases left for implementation.


text:
Celsius - Fahrenheit anagram
Task

Make a complete program or a function which calculates sum of all temperatures which, when written in Celsius and Fahrenheit scale, are anagram of each other.

Description
For example, 275 degree Celsius = 527 degree Fahrenheit, and 527 is anagram of 275. Non-integer temperatures (either in degree Celsius or degree Fahrenheit) and temperatures colder than 0 degree Celsius (like -40C = -40F) will not be considered.
Input
Input is a temperature in format ([1-9][0-9]*)(C|F) (example: 42F = 42 degree Fahrenheit, 125C = 125 degree Celsius, ...).
The program should be able to handle temperature less than 1000000C.
Output
Output is sum of all temperatures less than the temperature given by input, which, when written in Celsius and Fahrenheit scale, are anagram (without leading zeroes) of each other. Output will be two integers separated by a space. The first one will be the sum in degree Celsius, and the second one will be the sum in degree Fahrenheit.
If there's no such temperature, return or output 0 0.
Example

Input : 42C

There's no such temperature
Output : 0 0

Input : 300C

There's one temperature : 275C = 527F
Output : 275 527

Input : 10000F

There're three temperatures : 275C = 527F, 2345C = 4253F, and 4685C = 8465F
Output : 7305 13245

Hm, so 275 Coulomb are 527 Farad? ;-)

I assume you want to exclude temperatures less than 0°C?

@dan04 Yes. No temperatures less then 0 degree Celsius will be considered.

GolfScript, 65 61 characters
)\~{32- 9/5*}@70=*5/),0.@{.5*.`$@9*32+.`$@=:f*@+\f*@+\}%]' '*

Edit: incorporating the reduce operation into the loop saved 4 characters

C and F are different parities, so you can probably save a char by replacing 70= with 1& and working in the other scale.

@PeterTaylor Thank you for this hint. I also thought about that one but the other scale requires an offset of 32 which costs me 2 chars. Maybe I have to think about that again...

C# - 166
Due to the small number of matches, I thought it might be easier to hardcode the outputs:
void F(string i){int n=int.Parse(i.Substring(0,i.Length-1));
n=i.Last()=='C'?n:5*(n-32)/9;
Console.Write(n>4685?"7305 13245":n>2345?"2620 4780":n>275?"275 527":"0 0");}

Edit: 352
To do it right requires a bit more work. Here's a first attempt at using a whole pile of linq:
using System;
using System.Linq;
class P{static void Main(string[] i)
{
   int n=int.Parse(i[0].Substring(0,i[0].Length-1));
   n=i[0].Last()=='C'?n:5*(n-32)/9;
   var q=Enumerable.Range(1,n).Where(x=>new string(((decimal)x*9/5+32).ToString().OrderBy(y=>y).ToArray())==new string(x.ToString().OrderBy(y=>y).ToArray()));
   Console.Write(q.Sum()+" "+q.Sum(x=>x*9/5+32));
}}

Maybe the 'use a pile of linq instead of a loop' approach hurt me too much. I'll try and shorten it.
Edit 2: 356
Since I'm already way behind in raw count, here's a one-liner from hell:
Console.Write(Enumerable.Range(1,i.Last()=='C'?int.Parse(i.Substring(0,i.Length-1)):5*(int.Parse(i.Substring(0,i.Length-1))-32)/9).Where(x=>new string(((decimal)x*9/5+32).ToString().OrderBy(y=>y).ToArray())==new string(x.ToString().OrderBy(y=>y).ToArray())).Aggregate("0 0",(a,t)=>(int.Parse(a.Split(' ')[0])+t)+" "+(int.Parse(a.Split(' ')[1])+t*9/5+32)))

Your program does not give the correct result if the input exceeds 10985C.

Dang. my mind must have skipped one of the zeroes in the problem statement. I could've sworn it said it only had to handle 10k and under.

You can save 12 chars by replacing i[0].Substring(0, i[0].Length - 1) with i[0].Split('C','F')[0] :)

Mathematica, 77
I wish I could get this shorter, but working with function names like IntegerDigits I think this is about the best I can do.
 Grid@{Total@Select[{#,9/5#+32}&~Array~#,SameQ@@(Sort@IntegerDigits@#&)/@#&]}&

Perl, 182 characters
sub F{5*($_[0]-32)/9}sub C{$_[0]*9/5+32}sub O{join'',sort split//,shift}<>=~/.$/;$c=$&;@s=(0,0);map{$v=&$c($_);if(O($_)==O($v)){$s[0]+=$_;$s[1]+=$v;}}0..$`;@s=sort{$a<=>$b}@s;say"@s"

MATL, 44 47 bytes
0&)Uqw70=?32- 5*9/]OOhw:"@t9*5/32+VY@Um?@4MhvXs

Try it online!
(+3 bytes to output 0 0 for no such temperatures (instead of empty output).)


text:
Shortest code that raises a SIGSEGV
Write the shortest code that raises a  Segmentation Fault (SIGSEGV) in any programming language.

Wow. Possibly the shortest successful question.

@MatthewRoh Out of interest, I made this SEDE query. It looks like there are a few with +10 or higher, but this is the first above +40

C, 5 characters
main;

It's a variable declaration - int type is implied (feature copied from B language) and 0 is default value. When executed this tries to execute a number (numbers aren't executable), and causes SIGSEGV.
Try it online!

Default value may not be 0, and this may give a BUS error rather than a segmentation fault.

@Macmade: Actually, it is 0. static variables start as 0, and main; is static, as I declared it outside function. http://c-faq.com/decl/initval.html

last time i played with this thing, i figured out that there's a different reason for the segfault. First of all by calling main you jump to the location of main, not the value, another thing is main is an int, it's located in .bss, usually functions are located in .text, when the kernel loads the elf program it creates an executable page for .text and non-executable for .bss, so by calling main, you jump to a non-executable page, and execution something on a such page is a protection fault.

Yep, segfaults in C are pretty much the default :P

main __attribute__((section(".text#")))=0xc3; FTFY (at least it seems to return without crashing on my x86).

@jozxyqk Or shorter, const main=195;. As interesting it is that it's working, the goal of this code golfing challenge was to make the code segfault, not work :).

cont main=195; doesn't work anymore, it gets in the .rodata section which is readable but not executable.

Bash, 11
kill -11 $$

Signal 11 in 11 characters. Seems legit.

@nyuszika7h I was going to upvote your comment, but you have 11 upvotes right now, so I'm going to leave it at that. :P

@AlexL. other people seem to have spoiled that :(

@theonlygusti Yeah... That's too bad. :( Oh well, then I can upvote it now.

Up to 42 upvotes, no touchee!

@JoeyAdams My shell script terminal just loaded for a long time, no segfault.

@theonlygusti it's okay, at least you can have 11! Until someone ruins that too.

Assembly (Linux, x86-64), 1 byte
RET

This code segfaults.

As an MSDOS .com file, it runs and terminates without error.

see this code http://ideone.com/RMuLf

My point being: just specifying “assembly” isn't enough to make it segfault.

'ret' by itself should be a valid program; I suspect that is an error in the emulator.

@JB: On MS DOS, no program will ever produce a segmentation fault. That's because MS DOS runs in real mode where memory protection is nonexistent.

@celtschk IIRC NTVDM will eke out on nonexistent addresses, and those not allocated to MS-DOS.

@celtschk: You can segfault it anyway like so: mov bx, 1000h ; shr ebx, 4 ; mov eax, [ebx] -> CPU raises the underlying SEGV (AFAIK there's nobody to handle it though).

Whether ret by itself crashes depends on whether there's an outer environment to return to.  For instance, if this is used as the body of main in a typical C environment, it will not crash (but it will exit with a garbage status), but if it's used as the sole contents of an ELF text segment, it typically will crash because the initial stack frame created by the OS has a null pointer for the return address.

I have modified the answer to count bytes instead of characters.

Python 2, 13
exec'()'*7**6

Windows reports an error code of c00000fd (Stack Overflow) which I would assume is a subtype of segmentation fault.
Thanks to Alex A. and Mego, it is confirmed to cause segmentation faults on Mac and Linux systems as well. Python is the language of choice for portably crashing your programs.

Segmentation fault: 11 on Mac

Segmentation fault (core dumped) on Linux

Does this hang up first?

@MegaMan As in take a long time to finish? No, 7**6 is only about 100K so there's no perceptible delay.

Why does this work? It doesn't seem to on Python 3.6.8 on Mac OS.

@MaxGasner Try reading the programming language again :)

why does it work on py2?

@MaxGasner https://www.stackoverflowbusiness.com/hubfs/B2B-SO/images/logo-so-PRINT-4.png

yes, obviously, but where? like is this a CPython implementation detail because the parser doesn't catch the syntax error early, etc.

"error code of c00000fd (Stack Overflow)" hey wait a minute i recognize that from somewhere

@MaxGasner: print and exec are no longer "statements" in Python 3, they MUST be used like functions: exec('()'*7**6) (15 bytes works on both Python 2 and 3)

Yeah, it doesn't work on 3.8.9 (or at least my build of 3.8.9) on OS X. -- at least this version is clever enough to instead give you aRecursionError

pdfTeX (51)
\def~#1{\meaning}\write0{\expandafter~\string}\bye

This is actually probably a bug, but it is not present in the original TeX, written by Knuth: compiling the code with tex filename.tex instead of pdftex filename.tex does not produce a segfault.

LOLCODE, 4 bytes
OBTW

Does not work online, only in the C interpreter.

LOL FANCY CODE M8 8/8 KTHXBYE

Python, 33 characters
>>> import ctypes;ctypes.string_at(0)
Segmentation fault

Source: http://bugs.python.org/issue1215#msg143236
Python, 60 characters
>>> import sys;sys.setrecursionlimit(1<<30);f=lambda f:f(f);f(f)
Segmentation fault

Source: http://svn.python.org/view/python/trunk/Lib/test/crashers/recursive_call.py?view=markup
This is the Python version I'm testing on:
Python 2.6.1 (r261:67515, Jun 24 2010, 21:47:49)
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin

In general the Python interpreter is hard to crash, but the above is selective abusiveness...

W32 .com executable - 0 bytes
This will seem weird, but on 32 bit Windows systems, creating and executing an empty .com file may cause a segfault, depending on... something. DOS just accepts it (the 8086 having no memory management, there are no meaningful segments to fault), and 64 bit Windows refuses to run it (x86-64 having no v86 mode to run a .com file in).

Bash, 4 bytes
Golfed
. $0

Recursively include the script into itself.
Explained
Recursive "source" (.) operation causes a stack overflow eventually,
and as Bash does not integrate with libsigsegv, this results in a SIGSEGV.
Note that this is not a bug, but an expected behavior, as discussed here.
Test
./bang
Segmentation fault (core dumped)

Try It Online !

Forth - 3 characters
0 @

(@ is a fetch)

Shortest one so far that will work on modern systems.

Which Forth? Gforth just says "Invalid memory address"

brainfuck (2)
<.

Yes, this is implementation-dependent. SIGSEGV is the likely result from a good compiler.

How is a compiler that segfaults on that "good"? That < should either have no effect or wrap around.

Immediately producing a runtime error on bounds violation is best because it lets the programmer find and fix the bug as fast as possible. Letting the buggy program run for a while and corrupt memory haphazardly before crashing just makes the problem harder to diagnose. Preventing the crash entirely, as you suggest, is worst; the programmer may get the program "working" and then be publicly humiliated when it crashes on standard compilers and interpreters.

Conversely, catching bounds violations before runtime is not possible in general, nor especially useful in the cases where it is possible. Producing a more descriptive runtime error would be okay, but having the operating system catch it as a segfault is great because it doesn't have any speed cost. (In case it's not clear, the compiler itself doesn't segfault--it produces executables that segfault as soon as they try to access memory out of bounds.)

Can you provide an implementation that produces this behavior and was created before this challenge was posted? If not, this answer is invalid.

Bounds checks are implementation specific, so I'm sure there are some that would error on it. Would any SIGSEGV though? I doubt it. There are a large number of programs that depend on the array wrapping to the left though. It can be rather convenient having growable storage on both sides.

My compiler for Sun machines gave SIGSEGV, as of version 1.1 released in 2004. (http://web.archive.org/web/20040815081834/http://www.hevanet.com/cristofd/brainfuck/dbc.c) Because it was pretty obviously the best thing to do. (Any counterarguments?) I haven't done a survey of other people's brainfuck compilers that generate machine-language executables. If I bother I'll report back here afterward. (Because having array space available to the left is nonstandard, careful brainfuck programmers won't use that space deliberately. So it's helpful to let them know ASAP when they use it accidentally.)

Some brainfuck implementations let you go out into the wild west, and allocate tape memory (and do memory magicks) for you if you do so. So yes, it is implementation defined.

Some do. Because many (if not most) do not, this "feature" is only used by those who don't care about making their programs portable or those who aren't thinking about it. For people who want to be careful, bounds checking is more useful.

Perl ( < 5.14 ), 9 chars
/(?{??})/

In 5.14 the regex engine was made reentrant so that it could not be crashed in this way, but 5.12 and earlier will segfault if you try this.

I can reproduce this on Perl 5.14 (Debian) and 5.18 (Arch Linux). http://sprunge.us/RKHT

Reproduced with Perl v5.20.2 (windows)

What about /(?R)/ on older Perl versions?

C, 18
main(){raise(11);}

do you need to add #include <signal.h> in the code listing?

@FlorianCastellane: in C90 and lower, for any function call done without a visible declaration, the compiler implicitly declares it as int func(). i.e. a function returning int, taking unspecified parameters. In this case raise is a function returning int, taking an int argument, so this works out (even if the compiler complains).

@Hasturkun main(){main();}

Haskell, 31
foreign import ccall main::IO()

This produces a segfault when compiled with GHC and run.  No extension flags are needed, as the Foreign Function Interface is in the Haskell 2010 standard.

Awwww. I was gonna post import Foreign;main=peek nullPtr::IO Int, but that's 40.

C - 11(19) 7(15) 6(14) 1 chars, AT&T x86 assembler - 8(24) chars
C version is:
*(int*)0=0;

The whole program (not quite ISO-compliant, let's assume it's K&R C) is 19 chars long:
main(){*(int*)0=0;}

Assembler variant:
orl $0,0

The whole program is 24 chars long (just for evaluation, since it's not actually assembler):
main(){asm("orl $0,0");}

EDIT:
A couple of C variants. The first one uses zero-initialization of global pointer variable:
*p;main(){*p=0;}

The second one uses infinite recursion:
main(){main();}

The last variant is the shortest one - 7(15) characters.
EDIT 2:
Invented one more variant which is shorter than any of above - 6(14) chars. It assumes that literal strings are put into a read-only segment.
main(){*""=0;}

EDIT 3:
And my last try - 1 character long:
P

Just compile it like that:
cc -o segv -DP="main(){main();}" segv.c

in C isn't       main;     only 5 charecters

@Arya: Huh? What do you mean?

only  main;in file.c

:Linker doesn't check whether main is function or not .It just pass it to the loader and return sigsegv

@Arya: Now I got it. Yep, your kung fu is better.

@Alexander---smart programmer

@Arya That may run fine (if it happens that the bytes at main appear to form valid instructions) or raise an SIGILL instead.

@FUZxxl In this case main is a zero-initialized global int variable, so what we get is a result of trying to execute some zero bytes. In x86 it'd be something like add %al,(%rax) which is a perfectly valid instruction which tries to reach memory at address stored in %rax. Chances of having a good address there are minimal.

Of course the last entry can be used for everything, you just have to supply the right compiler arguments. Which should make it the automatic winner of any code golf contest. :-)

Usually compiler flags other than ones that choose the language version to use are counted towards the total.

Perl, 10 / 12 chars
A slightly cheatish solution is to shave one char off Joey Adams' bash trick:
kill 11,$$

However, to get a  real segfault in Perl, unpack p is the obvious solution:
unpack p,1x8

Technically, this isn't guaranteed to segfault, since the address 0x31313131 (or 0x3131313131313131 on 64-bit systems) just might point to valid address space by chance.  But the odds are against it.  Also, if perl is ever ported to platforms where pointers are longer than 64 bits, the x8 will need to be increased.

What is this 1x8 thing?

@HannesKarppila It's a short way to write "11111111".

You can replace 1x8 with $^, it's long enough in both 32 and 64 bit.

Python 33
import os
os.kill(os.getpid(),11)

Sending signal 11 (SIGSEGV) in python.

Also 33 characters: from os import* and kill(getpid(),11)

F90 - 39 bytes
real,pointer::p(:)=>null()
p(1)=0.
end

Compilation:
gfortran segv.f90 -o segv

Execution:
./segv

Program received signal SIGSEGV: Segmentation fault - invalid memory reference.

Backtrace for this error:
#0  0x7FF85FCAE777
#1  0x7FF85FCAED7E
#2  0x7FF85F906D3F
#3  0x40068F in MAIN__ at segv.f90:?
Erreur de segmentation (core dumped)

Materials:
gfortran --version
GNU Fortran (Ubuntu 4.8.4-2ubuntu1~14.04.1) 4.8.4

Nice first post.

dc - 7 chars
[dx0]dx

causes a stack overflow

Is works, but can you elaborate? Why does it behave that way?

[dx0] stores dx0 on the stack, then d duplicates the top stack element, then x pops the top stack element (dx0) and executes it. Which duplicates the top stack element, and starts executing it... the 0 needs to be there to prevent this being a tail call, so they all build up.

PicoLisp - 4 characters
$ pil
: ('0)
Segmentation fault

This is intended behaviour. As described on their website:

If some programming languages claim to be the "Swiss Army Knife of Programming", then PicoLisp may well be called the "Scalpel of Programming": Sharp, accurate, small and lightweight, but also dangerous in the hand of the inexperienced.

Actually, 17 16 11 10 9 bytes
⌠[]+⌡9!*.

Try it online!
If the above doesn't crash, try increasing the number (multi-digit numbers are specified in Actually with a leading colon)
Crashes the interpreter by exploiting a bug in python involving deeply nested itertools.chain objects, which actually uses to implement the + operator.

OCaml, 13 bytes
Obj.magic 0 0

This uses the function Obj.magic, which unsafely coerces any two types. In this case, it coerces 0 (stored as the immediate value 1, due to the tag bit used by the GC) to a function type (stored as a pointer). Thus, it tries to dereference the address 1, and that will of course segfault.

it coerces 0 (stored as the immediate value 1) - why is 0 stored as 1?

@Skyler see edit

Obj.magic()0 is one char shorter :)

Pyth, 3 characters
j1Z

This would be the part where I explain how I came up with this answer, except I legitimately have no clue. If anyone could explain this for me, I'd be grateful.
Here it is in an online interpreter.

Explanation
j squares the base and calls itself recursively until the base is at least as large as the number. Since the base is 0, that never happens. With a sufficienly high recursion limit, you get a segfault.
- Dennis ♦

Figured something out! From browsing Pyth's source, I found that this code does j on 1 and 0, which tries to convert 1 into base 0. Why that segfaults, I have no idea...

See here. j squares the base and calls itself recursively until the base is at least as large as the number. Since the base is 0, that never happens. With a sufficienly high recursion limit, you get a segfault.

@Dennis IDEone

@SeeRhino The Pyth interpreter sets the recursion limit to 100,000. At least on TIO, that's enough for a segfault.

Python 3.8+, 47 bytes
eval((lambda:0).__code__.replace(co_consts=()))

Not the shortest python entry by far, but this one works without any imports. And as a bonus, this bug is exploitable to get arbitrary code execution, if you're smart about it.

Welcome to Code Golf, this is a pretty interesting answer!

It's honestly amazing that this language that has such a simple interface when seen from above gives you such incredibly deep access into the language's own runtime internals.

19 characters in C
main(a){*(&a-1)=1;}

It corrupts return address value of main function, so it gets a SIGSEGV on return of main.

It depends on the stack frame layout, so in some architecture it can possibly not fail.

Why not simply main;, or main(){*""=0;}?

@Sapphire_Brick main; is already given in another answer.

@saeedn Then why post it at all? This one isn't even the second to shortest!

@Sapphire_Brick At the time I was posting mine, main; wasn't posted and I didn't know it works. I was only pointing out that it is already given and no point in changing my answer. Furthermore, people here don't just post only for the shortest, sometimes a different way of solving the problem is also interesting.

@saeedn You're right; I can't blame you for posting an answer that was later surpassed. Regarding your second point, the title explicitly says the shortest code.

C# - 62
System.Runtime.InteropServices.Marshal.ReadInt32(IntPtr.Zero);

C# /unsafe, 23 bytes
unsafe{int i=*(int*)0;}

For some reason I don't understand, *(int*)0=0 just throws a NullReferenceException, while this version gives the proper access violation.

The int i=*(int*)0; returns a NullReferenceException for me.

You can try to access a negative location, like *(int*)-1=0 and get an access violation.

The particular exception is just what the clr wraps it in, and is insignificant. The os itself actually gives the seg fault in all these cases.

The reason why *(int*)0=0 throws an exception is likely due to optimization. Specifically, to avoid the cost of checking for null, the optimizer may remove null checks, but when a segfault occurs it may rethrow it as a proper NullReferenceException.

Cython, 14
This often comes in handy for debugging purposes.
a=(<int*>0)[0]

J (6)
memf 1

memf means free memory, 1 is interpreted as a pointer.

Why 1 rather than 0? Is it legal to free a null pointer in J?

Matlab - Yes it is possible!
In a response to a question of mine, Amro came up with this quirk:
S = struct();
S = setfield(S, {}, 'g', {}, 0)

Please give Matlab version -- R2015B (and 2016B also) just throws an error: Error using setfield (line 56)
At least one index is required.

@FlorianCastellane Not able to try all versions now, but it has been confirmed to give a segfault in quite some versions, the latest being 2014b and the earliest 2012a.

C - 14 chars
Be sure to compile an empty file with cc -nostartfiles c.c

Explanation:
What went wrong is that we treated _start as if it were a C function, and tried to return from it. In reality, it's not a function at all. It's just a symbol in the object file which the linker uses to locate the program's entry point. When our program is invoked, it's invoked directly. If we were to look, we would see that the value on the top of the stack was the number 1, which is certainly very un-address-like. In fact, what is on the stack is our program's argc value. After this comes the elements of the argv array, including the terminating NULL element, followed by the elements of envp. And that's all. There is no return address on the stack.

I'm pretty sure you have to score with the additional args

You have to add 14 bytes for the special flag.

@ErikGolferエリックゴルファー -nostartfiles is actually 13 bytes long :)

@CharlesPaulet I think you have to count the space too.

Rust, 34 bytes
fn main(){unsafe{*(0 as*mut _)=3}}

Just a null pointer assignment, nothing special here.

As a bonus, 45 44 40 bytes solution not using unsafe. Arguably a bug in a compiler.
#![no_main]#[no_mangle]static main:i8=0;

Main is usually a function ;).

Phooey, Interpreter Bug, 2 bytes
<?

Try it online!
This interpreter is so buggy it is beautiful. I can cause a bad free() with one byte of code in two ways. But that, unfortunately, is a SIGABRT.
A quick check of the source code will tell you that the interpreter does not support wrapping. However, the bug isn't "lul I read backwards and it crashes", it is a little more in depth.
The Phooey code translates to these function calls:
< tape.left(1) // move left one cell
? debug() // print debug info

So let's step through it:
First, we call tape.left(1).
    void left(int64_t amount) {
        right(-amount);
    }

This turns into tape.right(-1):
    void right(int64_t amount = -1) {
        pointer += -1;

Adding -1 to pointer results it being -1, since the initial value was zero.
However, let's double check what type pointer is:
    size_t pointer = 0;
    size_t furthest = 0;

pointer is a size_t, which is an unsigned type, meaning that this -1 turns into a REALLY big number. Specifically, SIZE_MAX, the largest object size C++ is allowed to handle.
        if(pointer > furthest)
            furthest = pointer;

We assign pointer to furthest, because SIZE_MAX > 0.
Now, we call debug():
void Phooey::debug() {
    std::cout << "Tape: " << tape << std::endl;
}

And this calls the operator overload function for std::ostream << Tape, and here is our bug:
std::ostream& operator<<(std::ostream& stream, Tape& tape) {
    for(size_t i = 0; i <= tape.furthest; i++) {
        stream << tape[i];
    }
}

Let's substitute tape.furthest, if the bug wasn't clear enough:
    for(size_t i = 0; i <= SIZE_MAX; i++) {
        stream << tape[i];
    }

This loop will keep reading data from the tape pointer and printing it, until it segfaults. It is actually an infinite loop otherwise: Since tape.furthest is SIZE_MAX, it will always be true, as SIZE_MAX + 1 == 0.
How ironic that the bug occurs in the debug() function.
A simple way to fix this would be to add wrapping support, making sure that the pointer is always in range. As a matter of fact, almost every bug in this program can be fixed with range checks.
Bonus!
debug() is the buggiest function in this program. It segfaults even without putting any ?s in your code!
<3-509

Try it online!
You may be saying, "How are you calling debug() without ??
And the answer is: ROP.
Specifically, on this exact build of Phooey, the tape is stored on the stack, and cells[-3] contains the return address from call Phooey::run(), 0x403957.
509 bytes before that is just after Phooey::debug() sets up its stack frame. (If I set the pointer to the start of the function, it crashes too early to be interesting since the stack is unaligned). That is why I subtract 509.
It segfaults because it is definitely NOT called how the code expects it to be, and rdi doesn't have the this pointer, so it crashes.
This is OBVIOUSLY going to be dependent on the system and binary itself.

Unix PDP-11 assembly, 18 bytes binary, 7 bytes source
(this is becoming a theme with me, maybe because it's the only language I sort of know that no-one else here does.)
inc(r0)

Increments the single byte addressed by the initial value of r0 [which happens to be 05162 according to the simh debugger] as of program start.
0000000 000407 000002 000000 000000 000000 000000 000000 000000
0000020 005210 000000

And, as always, the extraneous bytes at the end can be removed with strip.
I made a few attempts to get the source shorter, but always ended up getting either a syntax error or SIGBUS.

x86 and x86_64 machine language, 3 bytes
0:       50                      push   %eax
1:       eb fd                   jmp    0

This pushes the value of the EAX (or RAX in long mode) register to the stack in a loop until the stack overflows.
To try this, compile and run the following C program.
const char main[]="\x50\xeb\xfd";

To try it on Windows, prepend the following to mark main as executable.
#pragma section("foo", execute)
__declspec(allocate("foo"))

Main is not loaded in at address 0. As such, that jmp alone is causing the segfault. (I'm pretty certain,at least)

@moonheart08 it isn't jumping to absolute address 0, it's jumping to the push %eax. Jumping to absolute address 0 would require something like xor %eax, %eax; jmp *%eax

A long time later, i learned that the hard way (bugggssss!)
Thanks.

Squire commit 93d3bf1, 6 bytes
" "*-1

A quite intriguing blunder.
My initial attempt was to allocateth \$\text{II}^\text{LXIV}-\text{I}\$ bytes of memory, but alas, Squire thwarteth me by limiting string lengths to \$\text{XXXII}\$-bit integers, and even my peasant computer with a mere \$\text{VIII}\$ gigabytes of RAM was impervious to said attacks, but lo! Even if malloc rewardeth null, Squire containeth a defense stronger than steel:
void *xmalloc(size_t length) {
        void *ptr = malloc(length);

        if (ptr == NULL) {
                fprintf(stderr, "error allocating %zu bytes of memory\n", length);
                // Alas, thwarted again with SIGABRT!
                abort();
        }

        return ptr;
}

Instead, I ventured into value.c and spied this:
        case SQ_TSTRING: {
                sq_number amnt = sq_value_to_number(rhs);

                struct sq_string *result = sq_string_alloc(AS_STRING(lhs)->length * amnt + 1);
                // ...
        }

As with most strings in C, Squire terminateth all strings with \N, so Sampersand addeth \$I\$ whilst calculating the length.
Intriguingly, \$\text{I} \times -{\text{I}} + \text{I} == \text{N}\$. Therefore, this rewardeth &sq_string_empty.
struct sq_string *sq_string_alloc(unsigned length) {
        if (length == 0)
                return &sq_string_empty;
        // ...
}

To be more swift, Squire containeth some "static" strings for common values like "false" or "".
struct sq_string {
        char *ptr;
        int refcount;
        unsigned length;
        bool borrowed;
};

struct sq_string sq_string_empty = {
    .ptr = "",
    .length = 0,
    .refcount = -1,
    .borrowed = false,
};

Curiously, we have a string literal treateth as char *, which, despite its mutable appearances, is actually a member of the evil .rodata clan. These sneaky impostors are indistinguishable from normal strings, unless one encanteth -Wwrite-strings.
Returning to value.c, the next line triggers the .rodata impostor:
                // Lo! Sampersand hath summoned nasal demons!
                *result->ptr = '\0';

In order to make thine computer repent from nasal demons, thy great and powerful Linux exorcises Squire with a SIGSEGV.

I thoroughly enjoyed reading this

Ruby 3.x, 10 bytes
->x=(1in^x

Ruby doesn't like a circular pin reference in proc argument for some reason, this results in a null pointer dereference. Since this is a parser bug the program doesn't even have to be syntactically valid.

JavaScript Shell, 7 bytes
clear()

Clears absolutely everything, not just the current scope which obviously causes lots of borks which result in JS blowing up and segfaulting

According to MDN (document.clear), this should only do something in really old versions of Mozilla, and even then, what really segfaults in your experience?

@tomsmeding this is window.clear, FF directly doesn't reveal it, it's a spidermonkey built-in

Java (OpenJDK 9), 311 227 223 bytes
import sun.misc.*;import java.lang.reflect.*;class M{public static void main(String[]args) throws Exception{Constructor<Unsafe> c=Unsafe.class.getDeclaredConstructor();c.setAccessible(true);c.newInstance().getAddress(0);}}

Try it online!
Ungolfed:
import sun.misc.Unsafe;

import java.lang.reflect.Constructor;

public class SegFault {

    public static void main(String[] args) throws Exception {
        Constructor<Unsafe> unsafeConstructor = Unsafe.class.getDeclaredConstructor();
        unsafeConstructor.setAccessible(true);
        Unsafe unsafe = unsafeConstructor.newInstance();
        System.out.println(unsafe.getAddress(0));
    }
}

Saved 84 Bytes thanks to Mistah Figg

It does the same as the Dyvil Answer below

Ask the OP. After searching, I think Access Violation and SegFault are maybe two names for the same thing.

TIO throws a SIGSEGV on OpenJDK, so I think its Possible that Oracle and OpenJDK throws same things but under different names.

Why the long names and import x.y.asdf; instead of import x.y.*; ?

args -> a for a 3 byte savings

Remove the space before throws and the space before the declaration of c for a 2 byte savings

Using java.lang.reflect.Constructor instead of importing it saves 9 bytes

Try it online!

This can be shortened by using var "keyword" introduced in Java 10 to avoid typing the long type name of getDeclaredConstructor result.

Befunge-98 (FBBI), 1 byte
=

Try it online! (expand the Debug section to view the segfault)
This only works in the FBBI implementation of Befunge, exploiting a bug in its string handling code. Any attempt to read a string from an empty stack will result in a null pointer dereference. You can achieve the same result with the i (Input File) and o (Output File) instructions, which also expect a string on the stack.
Note that this error wouldn't occur if the stack was simply full of zeros, which in Befunge should be semantically equivalent to an empty stack. For it to crash the stack must be genuinely empty, as is the case on startup.

Tcl, 60 bytes
set a a;while {[incr i]<999999999} {set a [list $a]};puts $a

Not short, but crashes with a segfault.
This builds a deeply nested list (each with only one element), and when trying to serialize it, Tcl will crash with a stack overflow.
I have reported this bug here

Lua (luajit), 52 48 bytes
function f()c=coroutine;c.resume(c.create(f))end

An attempt to compete for the bounty that was recently set on an answer in Lua. This is a function submission (basically because I had to define a function anyway, so not including the code to run it saves bytes). Now with 4 bytes saved due to a suggestion by @ceilingcat to avoid repeating the word coroutine.
The program works by creating infinitely many coroutines, suspending each in turn to create and start the next. The most commonly used Lua interpreter, lua, thought of this case and starts causing coroutine creation to fail after a while. luajit, however, segfaults. (Valgrind reports the issue as a failure to grow the OS-defined stack; this is believable, seeing as one common coroutine implementation gives them each separate parts of the stack.)

Lua (LuaJIT), 47 43 bytes
f=require"ffi"f.cdef"int puts()"f.C.puts()

Uses FFI in LuaJIT to call puts() with no (valid) argument.

Ruby, 15 bytes
eval a='eval a'

Segfaults (Ruby 2.3 on Ubuntu xenial)

Lua 5.3.2 PUC-RIO (the "official") interpreter - 57 bytes
local t={}t.__newindex=t local y=setmetatable({},t)y[1]=1

Note: does not work on all machines, and was fixed in Lua 5.3.3.

Clean, 19 12 bytes
Start=code{}

Try it online!
Every function always returns something in Clean, including Start. Because we haven't specified the type of Start, the compiler assumes (and it can only assume when you inline ABC) that it takes no arguments. Since it takes no arguments, there's nothing on either stack when the function resolves, and so the runtime tries to evaluate the first node in the spine of a graph with... Zero nodes.

Nice, but the explanation is not entirely correct. The compiler knows the arity by the number of arguments of Start; there is no way to write a function in ABC that takes a number of arguments other than the number of arguments of the Clean function. On startup, a Start node is created. When it is evaluated, it is overwritten by _cycle_in_spine. The ABC code is supposed to push a new node on the stack, with which the _cycle_in_spine is then filled. But because it doesn't, the fill_a instruction then attempts to fill an uninitialised node above _cycle_in_spine.

@Keelan I learn something new every time you comment :). I'll edit that in once I'm back at my computer.

NASM, 3 characters.
any of the following:
ret
nop
cbw
cwd
cdq
clc
cld
cli
cmc
aaa
aas
aad
aam
stc
std
sti

ret causes stack underflow. cli and sti trigger SIGSEGV because they are privileged instructions.  All the other opcodes trigger a SIGSEGV simply because there's no exit point.

Under Linux, cli and sti will segfault all by themselves, because they're privileged, not because of the lack of exit point.  You could add hlt to the list for the same reason.

@NateEldredge Isn't hlt the opcode for "halt"? hlt causes the program to segfault, and does not halt the processor, even though the NASM manual (http://www.posix.nl/linuxassembly/nasmdochtml/nasmdoca.html#section-A.74) says it does.

Yes, hlt will halt the processor if executed at privilege level 0, but if not then it raises a general protection fault.  See for instance https://www.felixcloutier.com/x86/hlt.  Linux userspace programs are at privilege level 3, and the kernel handles the GPF by delivering SIGSEGV to the process.  cli and sti are in a similar boat, though the privilege requirements are more complicated.

@NateEldredge Ok, I've updated this answer.

Malbolge, 3046 bytes
Behold, an answer in Malbolge that you can embed inside an answer!
bP&A@?>=<;:9876543210/.-,+*)('&%$T"!~}|;]yxwvutslUSRQ.yx+i)J9edFb4`_^]\yxwRQ)(TSRQ]m!G0KJIyxFvDa%_@?"=<5:98765.-2+*/.-,+*)('&%$#"!~}|utyrqvutsrqjonmPkjihgfedc\DDYAA\>>Y;;V886L5322G//D,,G))>&&A##!7~5:{y7xvuu,10/.-,+*)('&%$#"yb}|{zyxwvutmVqSohmOOjihafeHcEa`YAA\[ZYRW:U7SLKP3NMLK-I,GFED&%%@?>=6;|9y70/4u210/o-n+k)"!gg$#"!x}`{zyxZvYtsrqSoRmlkjLhKfedcEaD_^]\>Z=XWVU7S6QPON0LKDI,GFEDCBA#?"=};438y6543s1r/o-&%*k('&%e#d!~}|^z]xwvuWsVqponPlOjihgIeHcba`B^A\[ZY;W:UTSR4PI2MLKJ,,AFE(&B;:?"~<}{zz165v3s+*/pn,mk)jh&ge#db~a_{^\xwvoXsrqpRnmfkjMKg`_GG\aDB^A?[><X;9U86R53ONM0KJC,+FEDC&A@?!!6||3876w4-tr*/.-&+*)('&%$e"!~}|utyxwvutWlkponmlOjchg`edGba`_XW\?ZYRQVOT7RQPINML/JIHAFEDC&A@?>!<;{98yw5.-ss*/pn,+lj(!~ff{"ca}`^z][wZXtWUqTRnQOkNLhgfIdcFaZ_^A\[Z<XW:U8SRQPOHML/JIHG*ED=%%:?>=~;:{876w43210/(-,+*)('h%$d"ca}|_z\rqYYnsVTpoRPledLLafIGcbE`BXW??TY<:V97S64P31M0.J-+G*(DCB%@?"=<;|98765.3210p.-n+$)i'h%${"!~}|{zyxwvuXVlkpSQmlOjLbafIGcbE`BXW??TY<:V97S64P31M0.J-+G*(D'%A@?"=<}:98y6543,1r/.o,+*)j'&%eez!~a|^tsx[YutWUqjinQOkjMhJ`_dGEaDB^A?[><X;9U86R53O20LKJ-HG*ED'BA@?>7~;:{y7x5.3210q.-n+*)jh&%$#"c~}`{z]rwvutWrkpohmPkjihafI^cba`_^A\[>YXW:UTS5QP3NM0KJ-HGF?D'BA:?>=~;:z8765v32s0/.-nl$#(ig%fd"ca}|_]yrqvYWsVTpSQmPNjMKgJHdGEa`_B]\?ZY<WVUTMR5PO20LK.IHA))>CB%#?87}}49zx6wu3tr0qo-nl*ki'hf$ec!~}`{^yxwvotsrUponQlkMihKIe^]EEZ_B@\?=Y<:V97S64P31M0.J-+GFE(C&A@?8=<;:{876w43s10qo-&%kk"'hf$ec!b`|_]y\ZvYWsVTpSQmlkNiLgf_dcba`C^]\?ZY;WV97SLK33HM0.J-+G*(D'%A$">!};|z8yw543t1r/(-,+*)(i&%fd"!~}|_t]xwvutslqTonmPkjLhKIedGEaZY^A?[Z=X:POT75QP31MFEJ-+**?DC&$@98=~|:{y7xv4us1rp.omll#('&g|#d!~a|{z\\qvuXsUkjoRPOOdihKfH^]bEC_B@\?=Y<:V97S6433HML/J,BAF)'&&;@?"=}549zxww.32s0p(',+*kj!&g$#d!~`|_]y\ZYYnsrUSohglOMihKfH^]bEC_B@\?=YX;V8NMR53O20L/-I,*FED'&A:#>=~;:z87xv4-,1rp.om+*ki'~}$ec!b`__tyx[vXnmrUSoRPlOMihgJIdcb[D_^A\[=Y<:V97SR5P2HGL/-IH+F(>=B%#?"~<}{9zx6wu3tr0/.on+*)('~g$#d!~`|{^y[qpuXVrqToQgfkNLhKIeHFbEC_B@\?=Y<:V97SRQ43NMLKJIHA*EDCBA#9>=<;{3z165.32+0q.-,+l)(h&ge#db~a_{^\x[YuXVrUSoRPlkjMLaJedGbaCBBW\[><XQPU86R53O20L/-I,*F)'C&$@#!=~|:98yx54-t10q.-m+lj(igff{"!b`|uty\ZvYWsVTpSQmPNjMKgJHdcbED_^]\U>YX;VU7S64PO2M/EDI,*F)'&&;@?"~<549zx6wu3tr0qo-nl*kihh}$#"cb}|{zyxqZutWrqSoRPlkNiKa`eHFbEC_^A\>TSX;9U86R53O20L/-I,*FED'&A@?>=<;:3z76543s+0/.-m%l#('&}${"c~}`{z\x[YuXVUUjonQlNdchKIedGEaZY^A?[><X;9U86R53O20//DIHG*)D=&A@#>=}||387x5u-,1rp.om+lj(igff{"!b}_uty\ZvYWsVTpSQmlkNMhgf_HcbE`_A]@>Z=;W:8T75Q42NM0.JCBG*(D'%A$">!};|zyy0543ts0/.-,%l)(i&%e#"c~`vuz][wZXtWUqTRnmPkMcbgJHdGEaDB^A?[ZY<;VUTSRQPI2MLKJI+AFEDC%;$9>=<5:38y65v32r0qonn%*)jh&}|#dbaav{z][wpotWUqTRnQOkjMKg`_dGEaDB^A?[><X;988MRQP32G0KJ-HG)ED'B$:9>!}||387x5u-,1rp.om+lj(ig%fd"ca}`^z][ZZotsrUTongPNNMhgf_dGbaD_^@\?=Y<:VU86RKJO20L/-,,AFE(C%;:?"~<;|9y105vt21rp.'&+*)ji&%${"c~}|{^yxZvYWsVTpoRPlediLJfIGcFD`CA]@>Z=;W:877LQPO21LKJIB+))(CBA@?8=~;:{87w5vt2sq/pn,+l)i!~%fd"!b}_uty\ZYYnsrUpRhglOMiLJfIGcFD`_^A@[ZYXWPU8SRQ4ONM//DIH+)E>=B%#?"~<}{9zx6wutt+0/pn,%$)jhgg|#"ca}vuz][ZZotsVTpihmPNMMbgfIGc\[`CA@@UZY<:VONSRQ4I2MLKJIH+dv'Ps$_"]~[|YzWxUvStQrOpMnKlIjGhEfCAAyxw`;zLxwpo#F!~joQmPNd<hKJr^GoEm~B@zzy,X;c(s&5QJmNGL.h-yTdEc=`;$LK=m|:FV7Cwe3craq_'J\H)jF&%B0/RQ

Try it online!

Rust, 38 33 bytes
unsafe{*(std::ptr::null_mut())=0}

Try it online!
Full program is fn main(){...}. Segfaults as setting a null pointer to a type is undefined behavior (hence the unsafe block that is required).
Old version:
unsafe{std::ptr::null::<u8>().read();}

There is something slightly poetic about a segfault in Rust

Jelly, 2 bytes
ßß

Try it online!
oh
Since ß isn't actually coded as a recursive function call in the underlying Python, it isn't affected by the recursion limit. I don't actually know how Jelly's quicks work under the hood, but this appears to just create a nested structure that grows until it can't anymore. Any atom or atom-like quick works after the first ß.

C++ (clang), compiler crash, 36 28 bytes
class{operator*(...){*this*1

Try it online!
Unlike the other compiler crash which I found on my own, I totally didn't look this one up on bugs.llvm.org..
Assembly (as, x64, Linux), 17 10 bytes
Unfortunately, this was not a segfault, but an assertion. Leaving it up with another compiler segfault as a bonus.
I wrote code that raises a SIGSEGV in assembler.
Literally.
Replace \0 with a literal 0x00 byte.
"\0.asciz "

Try it online!
Found this bug when golfing the assembly here
Note that this bug seems to have been fixed as of v2.34.

Rust, 17 bytes
fn main(){main()}

Try it online!
Well... This just calls itself.
It may be the only way to do it without unsafe.

It looks like Rust actually detects the stack overflow and aborts.. What version are you running?

But, it also is doing segfault, before aborting... as I found with strace

Oh, I guess you're right. My bad. Good find, then!

Perl 6, 22
shell "kill -11 $*PID"

Just shelling to whatever shell you have.

Why not do it directly in bash (11 chars): kill -11 $$...

Dyvil, 42 bytes
dyvil.reflect.ReflectUtils.UNSAFE.getInt 0

Explanation:
dyvil.reflect.ReflectUtils // qualified type name
     .UNSAFE               // accesses the static field UNSAFE in class
                           // dyvil.reflect.ReflectUtils, of type sun.misc.Unsafe
     .getInt 0             // calls the method sun.misc.Unsafe.getInt(long),
                           // which tries to read a 4-byte integer from
                           // the memory address 0

Whispers, 5 bytes
>> 1!

Try it online!
How it works
>> 1  - Call this line repeated
    ! - Prevent tail call

x86 .COM, 2 Bytes
66 61 POPAD

x86 .COM, 5 3 Bytes
A3 FF FF

Write to the segment border

Does that work? I thought that DOS runs in real mode and has no memory protection whatsoever.

@xfix in real mode segment limits are 0xFFFF

Haskell, 15 bytes
Causes a stackoverflow:
main=main>>main

Try it online!

You can use m@main=m>>m

I don't know about you, but I just get a SIGKILL.

Common Lisp (SBCL), 79 bytes.
SBCL captures pretty much every exception and signal, but we can cause an "Unhandled memory exception" which is the result of a SIGSEGV. We must tell SBCL to not consider type safety and just add a fixnum to a float, which ends up disastrous.
(defun f(x)(declare (optimize (safety 0))(fixnum x))(the fixnum (1+ x)))(f 0.0)

My SBCL image errors with:
Unhandled memory fault at #x14.
   [Condition of type SB-SYS:MEMORY-FAULT-ERROR]

Evaluating (f '(1 5)) returned a garbage object, then (gc) threw Lisp into the low-level debugger after it tried to GC that object presumably. I don't see the difference in results since it is possible to jump back into Lisp from this state, and I imagine this is 100% platform dependent behavior.

WebAssembly (WaWrapper), 12 bytes
(func $main)

Try it online!

x86 machine code - 1 byte
08048060 <_start>:
 8048060:       5c                       pop    esp

This is change value of address esp into value 0x1, and then raises a SIGSEGV.

(gdb) disassemble _start
Dump of assembler code for function _start:
   0x08048060 : pop    esp
End of assembler dump.
(gdb) b *0x08048060
Breakpoint 1 at 0x8048060
(gdb) r
Starting program: /home/user/programming/assembly/pop

Breakpoint 1, 0x08048060 in _start ()
(gdb) i r $esp
esp            0xbfffed40   0xbfffed40
(gdb) c
Continuing.

Program received signal SIGSEGV, Segmentation fault.
0x08048061 in ?? ()
(gdb) i r $esp
esp            0x1      0x1
(gdb)

Zig, 26 bytes
pub fn main()void{main();}

F95, 27 bytes
program a;pointer p;p=0;end

Try it online!

Could you provide a link to the language, and preferably a link to someone other users can run your code, such as TryItOnline!?

It works with GFortran, here’s 17 bytes

AArch64, 4 bytes
Raw machine code:
d65f03e0

Disassembly
        .globl f
f:
        ret     xzr

Branches to the xzr register, which is always null. We can't do something like str x0, [xzr] because it would be treated as sp.

pbrain, 1 byte
(

Try it online!
This is due to an unchecked error in the interpreter:
// Interpret a container of instructions
template<typename It> void interpret(It ii, It eos)
{
   while (ii != eos) {
      switch (*ii) {
         // Snip
         case '(':
            ++ii;

            {
               SourceBlock sourceBlock;

               while (ii != eos && *ii != ')') {
                  sourceBlock.push_back(*ii);
                  ++ii;
               }

               // BUG: eos is not handled here, and when ii is incremented below,
               // it is GREATER than eos, not triggering the loop condition,
               // which is if ii is EQUAL to eos, and causing an out of bounds read.
               //
               // It should be this:
               //   if (ii == eos) {
               //       throw 5; // raise error in the interpreter
               //   }

               procedures.insert(std::make_pair(mem[mp], sourceBlock));
            }

            break;
     }
     // Snip
     ++ii;
   }
}

For a version which doesn't rely on an implementation bug, behold, the world's least interesting segfault: the stack overflow from recursing too much.
(:):

It does exactly as you might expect, it defines a function and then calls itself recursively.

Python, 53 characters
class A:__lt__=lambda s,o:o.clear()or s
vars(A)>A()<0

This is a bit longer than some other solutions, but unlike some other solutions it

works in modern python versions (tested in 3.7.17, 3.8.17, 3.9.17, 3.10.12, 3.11.8 and 3.12.2)
doesn't look like it does anything dangerous/suspicious/illegal at first glance
showcases an actual interpreter crash rather than just explicitly dereferencing null/execing invalid code/etc

Btw, don't report this upstream, this issue is already known and closed as "wontfix" in CPython: https://github.com/python/cpython/issues/88004
Explanation:
The important part is essentially
class A:
    def __lt__(self, other):
        other.clear()

AnyClass.__dict__ > A()

AnyClass can be any class (A in the short version) and vars(A) is a shorthand for A.__dict__.
The issue here is that the class __dict__ property is supposed to be of type mappingproxy that is implemented as thin wrapper around regular dicts. This special type is supposed to make this dictionary immutable/read-only:
AnyClass.__dict__["foo"] = 0 # TypeError: 'mappingproxy' object does not support item assignment
del AnyClass.__dict__["foo"] # TypeError: 'mappingproxy' object does not support item deletion
AnyClass.__dict__.clear()    # AttributeError: 'mappingproxy' object has no attribute 'clear'

However, it's possible to circumvent this protection using python's data model. Specifically, mappingproxy doesn't reimplement all of the required methods itself, but instead just delegates to the underlying dict implementation.
So, when we do AnyClass.__dict__ > A() the following happens:

m = AnyClass.__dict__ is of type mappingproxy
a = A() is of type A

we try to execute m > a or m.__gt__(a)
mappingproxy doesn't implement __gt__, so it delegates this call to dict
this essentially does something similar to
# except this isn't a real property so it isn't accessible from pure python
d = m.__internal_reference_to_underlying_dict
return d.__gt__(a)

where d is the actual underlying storage of type dict, not the safe/immutable/read-only mappingproxy wrapper

we try to execute d.__gt__(a)
dict does implement __gt__, but it doesn't know what to do with our custom type A, so it returns the special NotImplemented value
python's data model says that when x.__gt__(y) (x > y) returns NotImplemented, you should try the swapped version y.__lt__(x) (y < x) before failing

we try to execute a.__lt__(d)
our custom class A does have an implementation for __lt__ that calls clear() on the "other" object, in this case - d

So with this, we were able to call clear() on the underlying storage for the class __dict__ that was supposed to be made immutable by exposing it through a mappingproxy. This breaks some core assumptions that python heavily relies on. After that, it's pretty easy to cause a SEGFAULT by attempting to interact with an instance of AnyClass (or A in the minified version).
The use of __lt__ and > here is not mandatory, this also works with any other paired binary operator (eq/ne, add/radd, sub/rsub, mul/rmul, etc).

Battlestar, 3 characters
ret

Test
 $ echo ret > main.bts
 $ bts main.bts
 (segfaults)

TI-BASIC, 5 bytes
Archive A:A

Archives the variable A and then tries to get the value of A.
Throws the ERR:ARCHIVED error when used.
This is the closest thing you'd get to a segmentation fault in TI-BASIC, since archived data cannot be accessed directly.
In other words, the software has attempted to access a restricted area of memory.

Note: TI-BASIC is a tokenized language.  Character count does not equal byte count.

It's not a segmentation fault.

@Sapphire_Brick It most definitely is.  "A segmentation fault occurs when a program attempts to access a memory location that it is not allowed to access, or attempts to access a memory location in a way that is not allowed (for example, attempting to write to a read-only location, or to overwrite part of the operating system)." (source)  Archived data can't be accessed in TI-BASIC, simple as that.  Do your research before commenting next time.

You seem to be saying "Fish can swim; I can swim, so I am a fish.". A segmentation fault is more specific than the definition you gave. It has to be the signal SIGSEGV, not just any memory permission error. Suppose you try to use a bash command that you don't have permission to use. Is that a segmentation fault? Of course not.

Fair enough.  Though, you could've explained that in a way without trying to use a strawman like "Fish can swim; I can swim, so I am a fish."

Io, 25 bytes
Recursively executing the current file raises a segmentation fault. (You know, the system running Io obviously doesn't implement tail-call optimization.)
doFile(System args at(0))

Try it online!

C++, 19 bytes.
int main(){main();}

Not very interesting, just stack overflow. (pun not intended)

Swift 5, 29 characters:
func x(){y()}
let y={x()}
x()

25 bytes

Go, 29 characters
package x;func x(y*int){*y=4}

x86 assembly (intel syntax), 12 chars
lgdt [0x123]

How it works
You force the cpu to load a GDT table at a random address(0x123 in this case) , and of course it'll segfault. And if that location is actually a valid gdt, you should still trigger a GPF. Also, this might triple fault if you use it on msdos.

Nim, 20 bytes
cast[ptr int](4)[]=2

Try it online!
Nim, 20 bytes
proc x()=x();x()
x()

Try it online!

Braille (reference interpreter bug), 9 bytes (3 UTF-8 chars)
⢽⢽⢹

Try it online!
⢽ data_pointer += 32768
⢽ data_pointer += 32768
⢹ data_pointer[15] += shared_storage

The Braille interpreter does not correctly handle memory allocation.
Specifically, it will only allocate the power of two larger than the program size in Braille opcodes. This supposed data pointer does not have much to work with.
Specifically, this program would allocate 4 bytes of memory. Technically, just one opcode (⢹) is enough to write out of bounds (since it is writing 15 bytes past a buffer that is 2 bytes large), but that sadly isn't enough to create a segfault. At least not on TIO.
This code will advance the data pointer 65536 bytes forward, then write to 15 bytes past that.
Since this is outside a 64 KB page boundary, it segfaults.

Bitwise, interpreter bug, 2 bytes
SL

Try it online!
Hooray for input validation.
SL expects 3 arguments, but I give it zero.
    for (line = 0; line < lines; line++) {
        char *t = strdup(s[line]);
        char *cmd = strtok(t," ");
        char *arg1 = strtok(NULL," ");
        char *arg2 = strtok(NULL," ");
        char *arg3 = strtok(NULL," ");

        //printf("%s %s %s %s\n",cmd,arg1,arg2,arg3);

        exec_cmd(cmd,arg1,arg2,arg3);

        free(t);
    }

strtok returns a null pointer since I don't supply the expected arguments, and when it dereferences it, it segfaults.
A rough fix:
int _register(char *index)
{
    if (index == NULL) {
        fprintf(stderr, "missing argument\n");
        exit(1);
    }
    // ...

Note: this also allows you to go past the tape bounds, but the state is a global variable so it isn't very useful for my ACE challenge.

Erlang 33
os:cmd("kill -11 "++os:getpid()).

You can invoke like
erl -eval 'os:cmd("kill -11 "++os:getpid()).'

Knight (C/golf), 0 bytes
Not that I would call this interpreter golfed...
A program that is empty (or all whitespace) segfaults.
If it is read from an empty file, getdelim() stores NULL into stream... (line 236)
    else getdelim(&stream,&size,'\0',fopen(argv[2],"r"));

And when the program does an initial scan for non-whitespace... (line 33)
    while(strspn(stream, "\t\n\f\r {}[]():#")) {

...it dereferences a NULL pointer.
Otherwise, it will increment the stream pointer (line 54)...
    ++stream;

...recurse into parse() ((line 68)
    func[1] = parse();

and give that same strspn() an out of bounds pointer (it might take a few recursions to hit a page fault).
Try it online!

Ok but that's kinda the point. It's only well defined for valid inputs and everything else is irrelevent ;p

Never said it wasn't. There are actually a lot of interpreters like this.

Pascal (FPC), 54 bytes
function _(x:int8):int8;begin _(0);end;begin _(0);end.

Try it online!

Free Pascal will not do any tail call optimize. So you may use procedure without parameter instead of a function: procedure _;begin _ end;begin _ end. would work the same.

MMIX, 8 bytes (2 instrs)
00000000: e0fffef5 a5a4ff00                    ṭ”“ṫʠƥ”¡

sflt    SETH $255,#FEF5
        STW  $164,$255

Attempting to do anything with any data at a negative address causes a segfault unless you're the OS. I picked trying to store two bytes to a mem-mapped IO device so it'd look cool with jxd.

Java 17 (OpenJDK), 180 177 172 bytes
import sun.misc.*;interface A{static void main(String[]a)throws Throwable{var f=Unsafe.class.getDeclaredFields()[0];f.setAccessible(true);((Unsafe)f.get(null)).getInt(0);}}

This may be JVM dependent, but I think this is the most compact way to do it.
Some strategies used:

An interface is used to get rid of the public modifier on the main function
A space isn't necessary between the array brackets and the variable name a
Throwable is more compact than the full name of the exception that could be thrown
var is used (Java 10 and up) instead of Field, also gets rid of an import
A direct array access to the declared fields is used (JVM dependent), for hotspot the main Unsafe instance is the first field in the class
getInt(0) is used because I'm pretty sure it has the lowest profile of any method that could cause a segfault in Unsafe
A wildcard import can be used rather than the explicit type name to cut down on text

Assembly (MIPS, SPIM), interpreter bug, 15 14 bytes
main:sb$0 f
f:

Try it online!
Here's a cute one I found by accident.
This attempts to store a byte to the address at label f. This is in the .text section.
SPIM is pretty clever in that writing out of bounds of a section will just grow the section. However, writing to .text is tricky.
SPIM stores instructions in a struct for easier parsing it and debugging, instead of just storing data directly.
CPU/inst.h:57:
/* Representation of an instruction. Store the instruction fields in an
   overlapping manner similar to the real encoding (but not identical, to
   speed decoding in C code, as opposed to hardware).. */

typedef struct inst_s
{
  short opcode;

  union
    {
      // Snip
    } r_t;

  int32 encoding;
  imm_expr *expr;
  char *source_line;
} instruction;

Therefore, to store to .text, SPIM will give it a special treatment in bad_mem_write().
CPU/mem.cpp:395:
void
set_mem_byte(mem_addr addr, reg_word value)
{
  data_modified = true;
  // .data
  if ((addr >= DATA_BOT) && (addr < data_top))
    data_seg_b [addr - DATA_BOT] = (BYTE_TYPE) value;
  // .stack
  else if ((addr >= stack_bot) && (addr < STACK_TOP))
    stack_seg_b [addr - stack_bot] = (BYTE_TYPE) value;
  // .data
  else if ((addr >= K_DATA_BOT) && (addr < k_data_top))
    k_data_seg_b [addr - K_DATA_BOT] = (BYTE_TYPE) value;
  // .text or section out of bounds
  else
    bad_mem_write (addr, value, 0); // <--
}

In bad_mem_write(), SPIM will attempt to splice and recompile the instruction as if you modified the memory directly.
CPU/mem.cpp:506:
static void
bad_mem_write (mem_addr addr, mem_word value, int mask)
{
  mem_word tmp;

  if ((addr & mask) != 0)
    /* Unaligned address fault */
    RAISE_EXCEPTION (ExcCode_AdES, CP0_BadVAddr = addr)
    else if (addr >= TEXT_BOT && addr < text_top)
  {
    // For halfword and byte writes, attempt to overwrite part of the instruction.
    switch (mask)
    {
    case 0x0:
      tmp = ENCODING (text_seg [(addr - TEXT_BOT) >> 2]);

#ifdef SPIM_BIGENDIAN
      tmp = ((tmp & ~(0xff << (8 * (3 - (addr & 0x3)))))
               | (value & 0xff) << (8 * (3 - (addr & 0x3))));
#else
      tmp = ((tmp & ~(0xff << (8 * (addr & 0x3))))
               | (value & 0xff) << (8 * (addr & 0x3)));
#endif
      break;
      // ...
    }

    // Free instruction if it isn't NULL
    if (text_seg [(addr - TEXT_BOT) >> 2] != NULL)
    {
      free_inst (text_seg[(addr - TEXT_BOT) >> 2]);
    }
    // create a new instruction with the encoding
    text_seg [(addr - TEXT_BOT) >> 2] = inst_decode (tmp);

But wait a second....
SPIM checks for NULL...
CPU/mem.cpp:549:
if (text_seg [(addr - TEXT_BOT) >> 2] != NULL)

...after it already dereferenced it!
CPU/mem.cpp:519 (after macro expansion)
tmp = text_seg [(addr - TEXT_BOT) >> 2]->encoding;

And what would cause this instruction to be NULL? If it is not an instruction.
And what is at the label f? Nothing, so SPIM dereferences a NULL pointer.

-1 byte: Parser abuse

I have submitted a patch fixing this but, but this works on at least 9.1.23 and earlier.

Trilangle, UB, 1 byte
If you allow undefined behavior that happens to segfault on my machine (Windows 10 on x64), all of the following programs work:

+
-
*
:
%
7
>
v
L
<
^
e
(
)
j
!
o
&
r
x
~
2

All of these attempt to perform some operation on an empty stack. Interestingly, , (pop from stack) runs just fine (though it loops forever).

.mmo (MMIX executable), 28 bytes (7 tetras)
Doesn't cause emulator segfault, but the program itself does segfault.
Negative addresses are reserved for the OS, and a fault occurs if the protection bit in rK is the same as the high bit of the instruction pointer, which it will be when the OS tries to start this program at the address given to start.
00000000: 98090100 980a00ff 8fe6a7d6 9b16daee  Ƭµ¢¡Ƭ½¡”Ɓȧʂẹɓæḷŀ
00000010: 980b0000 00000000 980c0001           Ƭ¿¡¡¡¡¡¡Ƭ€¡¢

98090100 lop_pre 1,0                // version 1, 0 tetras
980A00FF lop_post 255               // and immediately jump to postamble
8FE6A7D6                            // almost arbitrary address to start at
9B16DAEE                            // must have high bit set
980B0000 lop_stab
00000000                            // no tetras in symtab
980C0001 lop_end

C (gcc), 15 bytes
main(){main();}

So this is why Python has a recursion limit…
Try it online!

GFortran, compiler crash, 6 bytes
#if'a'

Try it online!
This answer is more appropriate for Crash your favorite compiler,
but that one is closed unfortunately.

Python 3.8, 14 bytes
This only works on Python 3.8 :P. I found this while scavenging bug reports.
*reversed({}),

Try it online!