title: Formula One Strategist

text:
# Question
Title: Formula One Strategist
# Introduction

Formula One is a complex sport and as with complex sports, strategy is very important.Some teams will manage better strategy than others and those teams will often win the races.

After last weekends' amazing German GP, which saw last years Champion Lewis Hamilton pit 6 times (in comparison, some races just have 1 stop per driver), I was really impressed with all the strategy that was involved by most of the teams. Some really great calls, such as going to soft (from inters) by Racing Point, saw their driver finish 4th which was a rare sight.

---

# Challenge

**Your task will be to suggest what tire configuration should be used for the race.**

---

**Tires**

Here are the 3 available tire types :

*All of this data unofficial data, this is unreal data that was made juste for a fun challenge. I tried to keep a little sense in choosing how durable the tires wowuld be, but as I repeat, this is UNOFFICIAL*

```
Name                           Soft   Medium   Hard
Degradation (per character)    15     10       8
Degradation (per corner)       263    161      128
Time delta (per corner) (ms)   0      +30      +45

```

There is no time delta on the straights so all tire perform the same

A tires life span is calculated by how many COMPLETE laps it can do before dying. It's health starts at `100 000` and will decrease by the degradation value in the above table.

---

**Pit**

You will be able to change tires by going to the pits but a pit stop will cost you time. That time is measured by the distance between P to P (the length EXCLUDES the `P`s on the start/finish straight multipled by 1750 milliseconds.

```
time for pits = (length between P to P) x 1750 ms

```

You must just complete the lap on the previous set of tires. So in a way, you are changing them at an imaginary line between the `#` and the character before it. Tire degradation in the pits are as if you were driving on track.

---

**Tracks:**

A corner is where the characters changes (look at exeption bellow)

All ascii characters can be used for the track (except the exceptions bellow that have specific meaning)

This does not count as a corner, it is just a kink. *This is just extra info seeing as the drawings are not considered official and just a representation to give users a better idea or to validate an algorithm.*

```
Ex 1
______
      ______

Ex 2
\
   \
      \

```

The `P` does not represent a corner , it is the pit entrance and exit. It still counts in track length though.

```
_____P_______________P__________

```

The `#` represents the start/finish line (the start and finish line will be the same for the purposes of simplifying things. They also count in track length. The race will start at an imaginary line between the # and whatever comes before it, so yes, the # will degrade the tires when the race starts. The `#` is also the first character in the input. You may assume that the last character of the track will be the same as the first character after the start/finish line (`#`).

---

# INPUT

The track:

1. A list/array of all the characters in order
2. A string with all the characters in order

Bonus. The track map drawing made out of the ascii characters (unofficial as it I won't garantee at this point int time that both the drawing and the string bellow are the same

Number of laps:

* An integer, however you want to receive it.

```
Ex.1 ["_P_#_P_||_______||", 250]
Ex.2 ["_","P","_","#","_","P","_","|","|","_","_","_","_","_","_","_","|","|"], 69

```

---

# OUTPUT

The tire strategy with 3 distinct characters to represent the 3 tire compound. Tires can be identified either with letters, numbers, or even words if you want.

You must output all the tires necessary for the race. Tire output must be from softest to hardest compouds.

```
Ex.1  [S, M, H]
Ex.2  [0, 1]
Ex.3  [Hard]

```

---

# OBJECTIVE

**TL;DR:** find the tire combination that optimizes time delta.

You must use all the tire data (constants) and the race data (track and number of laps, this will be your input) to optimize the best tire strategy (output) in order to minimize the time delta.

A time delta of 0 will be the perfect (but impossible) score, where you would run the soft tires (the fastest) the whole race. Thus, you must use a combinations of tires and run them for how many laps you want as long as it is still in the tires life span. Running soft for the whole race is fastest, but each time you change them at the end of a tire's life span, it will raise your time delta, because you must pit.

---

# Rules

* This is code golf so shortest code wins!
* The rest is almost a free-for-all (just don't hard code the answers in!)

---

# Example

Note, drawings are not offial, it is just for representation.

Also, the output aren't checked by another person then me yet, so if you are doing the challenge and find some errors, please notify me.

---

**1. Circuit de Spa-Francorchamps:** *(yes I know it looks like a gun, but it isn't gun related, I promise, Google the track if you want):*

```
                __________
        _____^^^          ___________________________
 _P_____                                             \___
<_____#_____P                                            |
             |_____________                  ________    |
                            \               /        |   |
                              \            /         |___|
                                \         |
                                 |        |
                                 |       _|
                                 |      |
                                 |______|

```

INPUT :

```
#_____<_P__________^^^_____________________________________\___||||___||________//|||_||______||||\\\_____________|P_____

44 laps per race (according to Wikipedia, Belgian GP 2018)

```

OUTPUT: `[Medium, Medium]`

---

**2. Autodromo Nazionale Monza:**

```
________
\       \
 \        \
  \          \
   \___        \
       \         \____
         \            \__________________________
           \                                      \
             \                                    /
               \ _____/___P__#_________P________/

```

INPUT :

```
#__P_____/_____\\\\\___\\\\________\\\\\____\__________________________\//________P_________

53 laps per race (according to Wikipedia, Italian GP 2018)

```

OUTPUT : `[Soft, Medium]`

---

**3. Circuit Gilles Villeneuve:**

```
            ____
       ____|    ____
    __/             \___________
   /    ____#___                _______
  /P___/        |P______________________>

```

INPUT :

```
#____/___P//__/____|________\__________________>______________________P|___

70 laps per race (according to Wikipedia, Canadian GP 2019)

```

OUTPUT : `[Soft, Soft, Medium]`

---

**4. Pocono Raceway *(not an F1 track, but here to test edge-cases)***

```
             / \
            /    \
           /       \
          /          \
         /             \
        /                \
       /                   \
      /                      \
     /                         \
    /                            \
   /                               \
  /                                  \
 /                                     \
  ________P______#_______________P_____

```

INPUT :

```
#_______________P_______\\\\\\\\\\\\\/////////////_________P_____

110 laps per race

```

*Number of laps is innacurate, according to USA Today, it is going to be 160 laps for the 2019 Sunday's Gander Outdoors 400, the 21st race in the Monster Energy NASCAR Cup Series. In F1, races are at least 305km, making any race around this raceway around 76 laps.*

OUTPUT : `[Hard]`

# Answer
# Jelly, ~~105~~ 102 bytes

```
³;`ẹ”PḊIḢ’×⁽£ż×’
ḟ⁾#PnƝS,L{ḋ“Ðẏ½Ƥ®x‘s2¤ÄUż“¡œ-‘¤ȷ5W¤÷Ḟµ⁴÷ḢḢĊ3ṗⱮẎịµZżÄŻ⁴_Ʋ{Ṃ€żʋ/>0Ḣ$ƇẈṪ,P€LÑ+SƲNƊƲ)MḢḃ3

```

Try it online!

A full program that takes the track as a string as its first argument and the number of laps as its second argument. Returns a list of integers representing 1 for soft, 2 for medium and 3 for hard.

## Explanation

### Helper link: calculate pit time from number of tyres needed

```
³                 | First argument for program (track as Jelly string)
 ;`               | Concatenate to itself
   ẹ”P            | Indices of "P"
      Ḋ           | Dequeue (remove first element)
       I          | Differences between consecutive numbers
        Ḣ         | Head (i.e. difference between indices of the 2nd and 3rd Ps in the concatenated track)
         ’        | Decrease by 1
          ×⁽£ż    | Multiply by 1750
              ×   | Multiply by:
               ’  | - Argument to this link subtracted by 1

```

### Main link: stage 1

```
ḟ⁾#P                                   | Remove all "#" and "P" from track
    nƝ                                 | Neighbours not equal (will return 1 for every change in symbol)
      S                                | Sum (i.e. number of corners)
       ,L{                             | Pair with length of original track
          ḋ                   ¤        | Dot product with following as a nilad: (Will calculate degradation per lap for each tyre type and also extra time for the corners; works because of the way Jelly vectorises)
                     ¤                 | - Following as a nilad
           “Ðẏ½Ƥ®x‘                    |   - 15, 248, 10, 151, 8, 120
                   s2                  |   - Split into twos [15,248],[10,151],[8,120]
                      Ä                | - Vectorised cumulative sum [15,263],[10,161],[8,128]
                       U               | - Vectorised reverse [263,15],[161,10],[128,8]
                        ż“¡œ-‘         | - Zipped with 0,30,45
                               ȷ5W¤÷   | Divide 100,000 by the first element of each (the degradation), leaving the additonal time per corner alone
                                    Ḟ  | Floor
                                     µ | Start a new monadic link with this as its argument

```

### Main link: stage 2

```
⁴÷          | Second argument (number of laps) divided by output of stage 1
  Ḣ         | Head (values for soft tyres)
   Ḣ        | Head (laps per tyre for aoft tyres)
    Ċ       | Ceiling (i.e. max number of tyres that might be needed)
     3ṗⱮ    | 3 to the Cartesian power of each number from 1 to the max number of tyres needed
        Ẏ   | Tighten (remove one level of lists)
         ị  | Index into output from stage 1
          µ | Start a new monadic link with this as its argument

```

### Main link: stage 3

```
                                 )     | For each of the possible tyre combinations:
Z                                      | - Transpose, so we have a list of laps per tyre set and another list of the extra time for corners per lap
           ʋ/                          | - Reduce using following as a dyad:
 ż    Ʋ{                               |   - Zip with following as a monad (applied to the list of laps per tyre set)
  Ä                                    |     - Cumulative sum
   Ż                                   |     - Prepended with zero
    ⁴_                                 |     - Subtracted from the number of laps
        Ṃ€                             |   - Minimum of each
          ż                            |   - Zip with additional time for corners
             >0Ḣ$Ƈ                     | - Filter those where the first number (the number of laps used for those tyres) is greater than zero
                              Ʋ        | - Following as a monad:
                  ẈṪ                   |   - Tail of the lengths (will be 2 if all laps accounted for, 1 if not)
                    ,        Ɗ         |   - Paired with following as a monad:
                     P€                |     - Product of each (additional time for each tyre set from corners for all laps driven)
                           Ʋ           |     - Following as a monad:
                       LÑ              |       - Helper link applied to length (number of tyre sets)
                         +             |       - Plus:
                          S            |         - Sum (of additional times for each tyre set)
                            N          |     - Negated
                                  M    | Indices of maximum
                                   Ḣ   | Head
                                    ḃ3 | Bijective base 3

```
> 1 votes

# Answer
# JavaScript (ES6), 234 bytes

Takes input as `(track)(laps)`, where `track` is an array of characters. Returns a string with \\$0\\$ = soft, \\$1\\$ = medium, \\$2\\$ = hard.

```
a=>k=>(a.map(c=>(C++,d+=P,c=='P'|c=='#'?P^=350:t+=p!=(p=c)),p=a[1],P=d=C=t=0),m=g=(n,L=k,x=0,o='')=>L?g(n>>2,L-=j=(j=1e5/(C*[15,10,8][n&=3]+t*[263,161,128][n]))>L?L:j|0,x-j*t*!!n*~n*3+d,o+n):(m=m<x|m==x&o>P?m:(P=o,x),n?P:g(++N)))(N=0)

```

Try it online!
> 3 votes

# Answer
# Python3, 557 bytes

```
E=enumerate
I=lambda t,c:(c+1)%len(t)
F=lambda t,C:t[C]not in{'P','#'}and t[I(t,C)]not in{'P','#'}and t[C]!=t[I(t,C)]
def f(t,l):
 H=100000
 T=[[15,263,0],[10,161,30],[8,128,45]]
 q=[(H,l,[i],0,0)for i,_ in E(T)]
 U=[]
 for h,l,u,r,c in q:
  if l==0:U+=[(u,r)];continue
  if c==0 and h<H:l-=1
  m=T[u[-1]]
  if'P'==t[c]:
   C,K,W=I(t,c),0,0
   while'P'!=t[C]:W+=1;K+=F(t,C);C=I(t,C)
   if h<m[0]*W+m[1]*K:
    for i,_ in E(T):q+=[(H,l,u+[i],r+W*1750,I(t,c))]
    continue
  q+=[(h-m[0]-F(t,c)*m[1],l,u,r+F(t,c)*m[2],I(t,c))]
 return min(U,key=lambda x:x[1])

```

Try it online!
> 0 votes

---
Tags: code-golf
---


title: Find Unique Anagrams

text:
# Question
Title: Find Unique Anagrams
Challenge Description: An anagram is a word or phrase formed by rearranging the letters of another word or phrase. For example, "listen" and "silent" are anagrams. In this challenge, your task is to write a program or function that takes a list of strings as input and returns the unique anagrams.

Write a program or function that takes a list of strings as input and returns the unique anagrams, preserving the order of appearance. Your solution should handle lowercase letters (a-z) only.

Examples:

| Input | Output |
| --- | --- |
| `["cat", "act", "tac", "dog", "god"]` | `["cat", "dog"]` |
| `["a", "ab", "abc", "abcd"]` | `["a", "ab", "abc", "abcd"]` |
| `["cat", "dog", "tac", "god", "act"]` | `["cat", "dog"]` |

The input list contains five strings. The strings "cat", "act", and "tac" are anagrams of each other, and "dog" and "god" are anagrams of each other. The output should contain only one representative from each group of anagrams, preserving the order of appearance. Hence, the output is `["cat", "dog"]`.

Requirements:

The input list can contain duplicate strings, and they should be considered as separate entities. The output should contain only one representative from each group of anagrams, preserving the order of appearance. The input list may contain an arbitrary number of strings. The input list and the output list can be empty.

This is , so the shortest solution in bytes is the winner.

Good luck!

# Answer
# Vyxal, 32 bitsv1, 4 bytes

```
⁽sġvh

```

Try it Online!

Works well.

## Explained

```
⁽sġvh
⁽sġ   # Group by sorting each word - groups based on first appearance of each word
  vh  # Get the first word in each group

```
> 4 votes

# Answer
# Jelly, 4 bytes

```
Ṣ€Ḣƙ

```

A monadic Link that accepts a list of lists and yields a list of lists containing the first of each anagram.

**Try it online!**

### How?

```
Ṣ€Ḣƙ - Link: list of lists, Words
Ṣ€   - sort each word
   ƙ - group Words by sorted_words and apply to each:
  Ḣ  -   head

```
> 5 votes

# Answer
# Ruby, 28 bytes

```
->l{l.uniq{|z|z.chars.sort}}

```

Try it online!
> 5 votes

# Answer
# 05AB1E, 6 bytes

```
.¡{}€н

```

Try it online or verify all test cases.

Or alternatively:

```
€{DÙkè

```

Try it online or verify all test cases.

**Explanation:**

```
        #  EXAMPLE INPUT: ["cat","tac","dog","god","act"]

.¡ }    # Group the words in the (implicit) input-list by:
  {     #  Sort the characters of the word
        #   STACK: [["cat","tac","act"],["dog","god"]]
    €   # Then map over each group of words:
     н  #  And only leave the first one
        #   STACK: ["cat","dog"]
        # (after which the list of remaining words is output implicitly)

€       # Map over each word of the (implicit) input-list:
 {      #  Sort the characters of the word
        #   STACK: ["act","act","dgo","dgo","act"]
  D     # Duplicate this list of individually sorted words
        #  STACK: ["act","act","dgo","dgo","act"],["act","act","dgo","dgo","act"]
   Ù    # Uniquify the copy list of strings
        #  STACK: ["act","act","dgo","dgo","act"],["act","dgo"]
    k   # Pop both, and get the indices of the remaining strings
        #  STACK: [0,2]
     è  # Use those indices to index into the (implicit) input-list of words
        #  STACK: ["cat","dog"]
        # (after which the list of remaining words is output implicitly)

```
> 4 votes

# Answer
# JavaScript (ES6), 43 bytes

```
a=>a.filter(s=>a[q=[...s].sort()]?0:a[q]=1)

```

Try it online!

### Alternate versions (same size)

```
a=>a.filter(([...s])=>a[s.sort()]?0:a[s]=1)

```

Try it online!

```
a=>a.filter(([...s])=>a[s.sort()]^(a[s]=1))

```

Try it online!

### Commented

```
a =>          // a[] = input array
a.filter(s => // for each string s in a[]:
  a[          //   test a[q]:
    q =       //     where q[] is the array
      [...s]  //     made of the characters of s
      .sort() //     sorted in lexicographical order
  ] ?         //   if a[q] is already defined:
    0         //     discard this entry
  :           //   else:
    a[q] = 1  //     set a[q] and keep this entry
)             // end of filter()

```
> 3 votes

# Answer
# APL (Dyalog Extended), 7 bytes

Anonymous tacit prefix function.

```
⊣/∧¨⊢⌸⊢

```

Try it online!

`⊣/` the first elements of

`∧¨` the each-sorted

`⊢⌸` grouping of

the argument
> 3 votes

# Answer
# Nibbles, 4.5 bytes (9 nibbles)

```
.=~$~`<$/

```

```
.=~$~`<$/
 =~         # group
   $        # the input
    ~       # without sorting the groups
     `<$    # by the results of sorting each element
.           # then map over this list of lists
        /   # folding over each list
            # (implicitly) returning the left-hand argument
            # (so returning the first element of each)

```
> 3 votes

# Answer
# Perl 5 `-nlF`, 23 bytes

```
$k{"@{[sort@F]}"}||=say

```

Try it online!

Input and output are one word per line.
> 3 votes

# Answer
# Pyth, 5 bytes

```
hM.gS

```

Try it online!

### Explanation

```
hM.gSkQ    # implicitly add k and Q
           # implicitly assign Q = eval(input())
  .g  Q    # group Q by lambda k
    Sk     #   sort k
hM         # take the first element of each group

```
> 3 votes

# Answer
# Husk, 2 bytes

```
üO

```

Try it online!

A not particularly clever solution, but seeing that Husk could solve this with half the bytes of other golfing languages I had to post it.

### Explanation

```
üO
ü     Remove duplicates from the list, keyed on
 O       the sorted strings

```

Basically `ü` does exactly what we need for this challenge: for each value in the input list, discard it if it is the same as any previous value when a function is applied to it. The function we use for this comparison is here simply the sorting function.
> 3 votes

# Answer
# Scala, 80 bytes

Golfed version. Try it online!

```
w=>{var s=Set[String]();w.filter(x=>if(s(x.sorted)) 0>1 else {s+=x.sorted;0<1})}

```

Ungolfed version. Try it online!

```
object Main {
  def main(args: Array[String]): Unit = {
    val list = List("cat", "act", "tac", "dog", "god")
    val distinctAnagrams = removeAnagrams(list)
    println(distinctAnagrams)
  }

  def removeAnagrams(words: List[String]): List[String] = {
    var seen = Map[String, Boolean]()
    words.filter { word =>
      val sortedWord = word.sorted
      if (seen.contains(sortedWord)) false
      else {
        seen += (sortedWord -> true)
        true
      }
    }
  }
}

```
> 2 votes

# Answer
# Wolfram Language (Mathematica), ~~38~~ 33 bytes

```
#&@@@#~GatherBy~Sort@*Characters&

```

Thanks to @att!
Try it online!
> 2 votes

# Answer
# , 70 bytes

```
\(x)x[match(unique(y<-sapply(x,\(s)intToUtf8(sort(utf8ToInt(s))))),y)]

```

Attempt This Online!

String manipulation isn't something R is good at.
> 2 votes

# Answer
# Japt, 9 bytes

Could be  if Japt had a built-in for grouping *without* sorting.

```
üñ mÎñ@bX

```

Try it

```
üñ mÎñ@bX     :Implicit input of array U
ü             :Group & sort by
 ñ            :  Sorting
   m          :Map
    Î         :  First element
     ñ        :Sort by
      @       :Passing each X through the following function
       bX     :  First index of X in U

```
> 2 votes

# Answer
# C# (Visual C# Compiler), 116 bytes

```
a=>a.Aggregate(new Dictionary<string,string>(),(d,i)=>{d.TryAdd(string.Concat(i.OrderBy(m=>m)),i);return d;}).Values

```

Try it online!
> 2 votes

# Answer
# Python 3, 91 bytes

```
def h(l):s=set();return[w for w in l if(x:=''.join(sorted(w)))not in s and (s.add(x) or 1)]

```

Attempt This Online

I wonder whether the filter expression can be shortened further.
> 2 votes

# Answer
# Haskell, 64 bytes

```
import Data.List
s=sort
a=map head.groupBy((.s).(==).s).sortOn s

```

Try it online!
> 2 votes

# Answer
# Julia 1.0, 17 bytes

```
!x=unique(sort,x)

```

Try it online!

input and output are a list of lists of characters

28 bytes with a list of strings as input and output: Try it online!
> 2 votes

# Answer
# C (gcc), 277 bytes

```
#define C(A,L)for(int i=A=0;L[i];L[i++]==t&&++A);
i,j,k,x,y,r,t;D(char*a,char*b){for(r=k=0;(t=a[k])||b[k];++k){if(!a[k]||!b[k]){++r;break;}C(x,a)C(y,b)x-y!=0&&++r;}}
main(int c,char**v){for(i=1;i<c;++i){for(j=i-1;j>0;--j){D(v[j],v[i]);if(r==0)goto B;}printf("%s ",v[i]);
B:1;}}

```

Try it online!

Readable version:

```
#define C(A,L)for(int i=A=0;L[i];L[i++]==t&&++A);

i,j,k,x,y,r,t;

D(char*a,char*b){
    for(r=k=0;(t=a[k])||b[k];++k){
        if(!a[k]||!b[k]){++r;break;}
        C(x,a)
        C(y,b)
        x-y!=0&&++r;
    }
}

main(int c,char**v) {
    for(i=1;i<c;++i){
        for(j=i-1;j>0;--j){
            D(v[j],v[i]);
            if(r==0)goto B;
        }
        printf("%s ",v[i]);
B:1;
    }
}

```

Explanation:

Not the most efficient approach but light on code: go through each item in the list (given as arguments), compare to each prior item using a difference function D, and print if none of them matched.

To check matching, the difference function goes through each character in the first string and counts the number of occurrences in either string of that character. If at any point either that number differs or we have finished processing one string while the other is still going, we consider the two non-matching.

To save bytes, I added the counting macro C, which accumulates into variable A the number of occurrences of global character t in list L.

-

# C (gcc), 303 bytes (alternate answer)

```
typedef unsigned long long u;n,i,j,k,z;u t;u y(n){return n==1?1:z*y(n-1)+1;}s(char* v){for(k=t=0;v[k];++k)t+=y(v[k]-96);}main(int c,char *v[]){long f[c];for(i=1;i<c;++i)for(j=0;v[i][j];++j>z&&++z);for(i=1;i<c;++i){s(v[i]);for(j=n,k=0;j>0;--j){f[j-1]==t&&++k;}if(k)continue;printf("%s ",v[i]);f[n++]=t;}}

```

Try it online!

Readable version:

```
typedef unsigned long long u;
n,i,j,k,z;u t;
u y(n){return n==1?1:z*y(n-1)+1;}
s(char* v){for(k=t=0;v[k];++k)t+=y(v[k]-96);}
main(int c,char *v[]) {
    long f[c];
    for(i=1;i<c;++i)for(j=0;v[i][j];++j>z&&++z);
    for(i=1;i<c;++i){
        s(v[i]);
        for(j=n,k=0;j>0;--j){f[j-1]==t&&++k;}
        if(k)continue;
        printf("%s ",v[i]);
        f[n++]=t;
    }
}

```

Explanation:

For sufficiently short strings, this alternate approach will work. We are calculating a signature, which is something like a checksum but reserving non-overlapping number ranges for the potential counts of each letter, for each given list item. We go through the items and then, each time we encounter a novel signature, we print the item and store the signature.

These signatures as currently calculated get *really* large *really* fast, so this will only work for short words. Realizing this, I switched to the other approach, but still thought it was interesting enough to include.

I suspect that with a little more work, this could not only work for arbitrarily-long arguments, but also do so with a lighter footprint than the first approach!
> 2 votes

# Answer
# Charcoal, 20 bytes

```
ＷＳＦ⬤υ⊙⁺ικ⁻№ιμ№κμ⊞υιυ

```

Try it online! Link is to verbose version of code. Takes input as a list of newline-terminated strings. Explanation:

```
ＷＳ

```

Repeat for each input string.

```
Ｆ⬤υ⊙⁺ικ⁻№ιμ№κμ

```

If none of the unique anagrams so far are anagrams of this string, then...

```
⊞υι

```

... add this string to the list of unique anagrams so far.

```
υ

```

Output the final list of unique anagrams.
> 1 votes

# Answer
# Arturo, 32 bytes

```
$=>[gather&=>sort|map[k,v]->v\0]

```

Try it!

Collect input strings in a dictionary where the key is the sorted string and the value is a list of strings that sort to that key, then map each dictionary entry to its first value. Input is taken as a list of lists of code points.
> 1 votes

# Answer
# Excel, 99 bytes

```
=LET(r,ROW(A:A),b,BYROW(A:A,LAMBDA(s,CONCAT(SORT(MID(s,r,1))))),FILTER(A:A,(b<>"")*MATCH(b,b,0)=r))

```

Note: This takes quite a long time to run on my weak machine and sometimes just locked Excel. For the sake of the screenshots below, I changed the range references from `A:A` to just `A1:A10`. The logic is all the same, though.

Input is one string per cell in column A.

* `LET(r,ROW(A:A)` creates an array of values 1 to 1,048,576 and assigns it to the variable `r`.
* `b,BYROW(A:A,LAMBDA(s,CONCAT(SORT(MID(s,r,1)))))` takes each string, splits it into pieces, sorts those pieces, and then combines them back into a string. The array of all these new, sorted strings is assigned to the variable `b`.
* `FILTER(A:A,(b<>"")*MATCH(b,b,0)=r)` filters out the values where that result array `b` is blank and then only returns the strings from the input array where their index in the input matches the first instance of their sorted string in the sorted string array `b`.

There are probably shorter ways to do this and I welcome someone pointing them out.
> 1 votes

# Answer
# PowerShell Core, 53 bytes

```
$args|?{($k="$($_|% t*y|sort)")-notin$s-and($s+=,$k)}

```

Try it online!

Takes the words arguments using splatting, returns a list or words.

It works by building a list of keys for each word by sorting its letters alphabetically:
e.g. `cat` has the key `a c t`
Then for each word `$_`, if the word's key `$k` is not in the list `$s`, add `$k` to `$s` and return `$_`
> 1 votes

# Answer
# simply, ~~105~~ 100 bytes

Yes, it's very long, but makes use of the built-in `&marsagain`.
(It's an anagram for `&is_anagram`, that happens to be 1 byte shorter.)

```
fn($x){$A=[]each$X in$x{$L=0each$a in$A if!$L$L=&marsagain($X$a)if!$L$A=&array_concat($A$X)}send$A;}

```

Defines an anonymous function that takes an array of strings and returns an array of strings.

---

---

## Ungolfed

This is the same code, but ungolfed.

### Code-like

```
anonymous function($words) {
    $anagrams = [];
    each $word in $words {
        $in_the_list = false;
        each $anagram in $anagrams {
            unless $in_the_list then {
                $in_the_list = &is_anagram($word, $anagram);
            }
        }

        unless $in_the_list then {
            $anagrams = &array_concat($anagrams, $word);
        }
    }

    return $anagrams;
};

```

### English-like

```
Set the variable $fn to an anonymous function with arguments($words)
Begin.
    Set the variable $anagrams = [].
    Foreach $word in $words
    Begin.
        Set the variable $in_the_list to false.

        Foreach $anagram in $anagrams
        Begin.
            Unless $in_the_list then
            Begin.
                Set the variable $in_the_list to the result of calling the function &is_anagram with the arguments ($word, $anagram).
            End.
        End.

        Unless $in_the_list then
        Begin.
            Set the variable $anagrams to the result of calling the function &array_concat with the arguments ($anagrams, $word).
        End.
    End.

    Return the value of $anagrams.
End.

```

Both variants do the same.

---

---

## Testing it

To test it, you have to assign it to a variable, E.g.:

```
$fn = fn($x){$A=[$x->0]each$X in$x{$L=0each$a in$A if!$L$L=&marsagain($X$a)if!$L$A=&array_concat($A$X)}send$A;};

// Copy-paste from the tests
$result = call $fn(["cat", "dog", "tac", "god", "act"]);

// Should output ["cat","dog"]
echo &json_encode($result);

```
> 1 votes

# Answer
# Factor \+ `sets.extras`, 22 bytes

```
[ [ sort ] unique-by ]

```

Factor has the perfect combinator for this, `unique-by`, which returns a list of the first unique values in a list after a function has been applied to each element. Requires Factor build ~2207+ for `sort`, hence this won't work on TIO or ATO.
> 1 votes

# Answer
# Thunno 2, 4 bytes

```
ñṠ€h

```

Attempt This Online!

#### Explanation

```
ñṠ€h  # Implicit input
ñṠ    # Group by sorting
  €h  # First item of each
      # Implicit output

```
> 1 votes

# Answer
# Uiua SBCS, 9 bytes

```
▽◰⍚(⊏⍏.).

```

Try it!

```
▽◰⍚(⊏⍏.).
        .  # duplicate
  ⍚(⊏⍏.)   # sort each string
 ◰         # mark firsts
▽          # keep

```
> 0 votes

---
Tags: code-golf, string, permutations
---


title: Shortest code that raises a SIGSEGV

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

# Answer
> 150 votes
# 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!

# Answer
> 94 votes
## Bash, 11

```
kill -11 $$

```

# Answer
> 52 votes
# Assembly (Linux, x86-64), 1 byte

```
RET

```

This code segfaults.

# Answer
> 36 votes
# 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.

# Answer
> 29 votes
# 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.

# Answer
> 27 votes
# LOLCODE, 4 bytes

```
OBTW

```

Does not work online, only in the C interpreter.

# Answer
> 22 votes
## 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...

# Answer
> 22 votes
# 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).

# Answer
> 20 votes
# 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 !

# Answer
> 19 votes
# Forth - 3 characters

```
0 @

```

(`@` is a fetch)

# Answer
> 18 votes
## brainfuck (2)

```
<.

```

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

# Answer
> 17 votes
# 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.

# Answer
> 16 votes
## C, 18

```
main(){raise(11);}

```

# Answer
> 14 votes
## 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.

# Answer
> 11 votes
## 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

```

# Answer
> 11 votes
## 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.

# Answer
> 11 votes
# Python 33

```
import os
os.kill(os.getpid(),11)

```

Sending signal 11 (SIGSEGV) in python.

# Answer
> 10 votes
# 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

```

# Answer
> 9 votes
# dc - 7 chars

```
[dx0]dx

```

causes a stack overflow

# Answer
> 9 votes
# 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.

# Answer
> 9 votes
# 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.

# Answer
> 8 votes
# 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.

# Answer
> 8 votes
# 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 ♦**

# Answer
> 8 votes
# 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.

# Answer
> 7 votes
## 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`.

# Answer
> 7 votes
## 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.

# Answer
> 7 votes
## Cython, 14

This often comes in handy for debugging purposes.

```
a=(<int*>0)[0]

```

# Answer
> 6 votes
## J (6)

```
memf 1

```

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

# Answer
> 6 votes
# 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)

```

# Answer
> 6 votes
# 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.

# Answer
> 6 votes
# 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 ;).

# Answer
> 6 votes
# 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.

# Answer
> 5 votes
## 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.

# Answer
> 5 votes
# 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"))

```

# Answer
> 5 votes
# 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`.

# Answer
> 5 votes
# 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.

# Answer
> 4 votes
# 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

# Answer
> 4 votes
# 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

# Answer
> 4 votes
# 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.

# Answer
> 3 votes
# 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

# Answer
> 3 votes
# 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.)

# Answer
> 3 votes
# 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.

# Answer
> 3 votes
## Ruby, 15 bytes

```
eval a='eval a'

```

Segfaults (Ruby 2.3 on Ubuntu xenial)

# Answer
> 3 votes
# 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.

# Answer
> 3 votes
# 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.

# Answer
> 3 votes
# 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.

# Answer
> 3 votes
# 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!

# Answer
> 3 votes
# 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();}

```

# Answer
> 3 votes
# 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 `ß`.

# Answer
> 3 votes
# 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.

# Answer
> 3 votes
# 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`.

# Answer
> 2 votes
## Perl 6, 22

```
shell "kill -11 $*PID"

```

Just shelling to whatever shell you have.

# Answer
> 2 votes
## 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

```

# Answer
> 2 votes
# Whispers, 5 bytes

```
>> 1!

```

Try it online!

## How it works

```
>> 1  - Call this line repeated
    ! - Prevent tail call

```

# Answer
> 2 votes
# x86 .COM, 2 Bytes

```
66 61 POPAD

```

# x86 .COM, ~~5~~ 3 Bytes

```
A3 FF FF

```

Write to the segment border

# Answer
> 2 votes
# Haskell, 15 bytes

Causes a stackoverflow:

```
main=main>>main

```

Try it online!

# Answer
> 2 votes
# 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.

# Answer
> 2 votes
# WebAssembly (WaWrapper), 12 bytes

```
(func $main)

```

Try it online!

# Answer
> 2 votes
### 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)

```

# Answer
> 2 votes
# Zig, 26 bytes

```
pub fn main()void{main();}

```

# Answer
> 2 votes
# F95, 27 bytes

```
program a;pointer p;p=0;end

```

Try it online!

# Answer
> 2 votes
## 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`.

# Answer
> 2 votes
# 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.

# Answer
> 2 votes
# 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

1. 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)
2. doesn't look like it does anything dangerous/suspicious/illegal at first glance
3. 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 `dict`s. 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:

0. `m = AnyClass.__dict__` is of type `mappingproxy`

`a = A()` is of type `A`
1. 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
2. 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
3. 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).

# Answer
> 1 votes
# Battlestar, 3 characters

```
ret

```

### Test

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

```

# Answer
> 1 votes
# 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.

# Answer
> 1 votes
# 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!

# Answer
> 1 votes
# C++, 19 bytes.

```
int main(){main();}

```

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

# Answer
> 1 votes
# Swift 5, 29 characters:

```
func x(){y()}
let y={x()}
x()

```

# Answer
> 1 votes
# Go, 29 characters

```
package x;func x(y*int){*y=4}

```

# Answer
> 1 votes
# **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.

# Answer
> 1 votes
# Nim, 20 bytes

```
cast[ptr int](4)[]=2

```

Try it online!

# Nim, 20 bytes

```
proc x()=x();x()
x()

```

Try it online!

# Answer
> 1 votes
# 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.

# Answer
> 1 votes
# 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.

# Answer
> 1 votes
## Erlang 33

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

```

You can invoke like

```
erl -eval 'os:cmd("kill -11 "++os:getpid()).'

```

# Answer
> 1 votes
# Pascal (FPC), 54 bytes

```
function _(x:int8):int8;begin _(0);end;begin _(0);end.

```

Try it online!

# Answer
> 1 votes
# 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`.

# Answer
> 1 votes
# 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!

# Answer
> 1 votes
# 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

# Answer
> 1 votes
# Assembly (MIPS, SPIM), interpreter bug, ~~<sup>15</sup>~~ 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.

# Answer
> 1 votes
# 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).

# Answer
> 0 votes
# .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

```

# Answer
> 0 votes
# C (gcc), 15 bytes

```
main(){main();}

```

So this is why Python has a recursion limit…

Try it online!

# Answer
> 0 votes
# 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.

# Answer
> 0 votes
# Python 3.8, 14 bytes

This *only* works on Python 3.8 :P. I found this while scavenging bug reports.

```
*reversed({}),

```

Try it online!

---
Tags: code-golf, error-message
---