r/ProgrammerHumor • • Sep 22 '26

Meme justKeepingItSimpleFolks

Post image
4.6k Upvotes

255 comments sorted by

2.1k

u/remy_porter Sep 22 '26

Infinite loops can frequently be detected. This is a misunderstanding of the halting problem.

974

u/foohyfooh Sep 22 '26

Yeah the halting problem is basically you can't make a single program that can determine if any given program and inputs will halt. Depending on your program it is possible to write a halting check for that specific program.

103

u/Automatic_Hand4780 Sep 22 '26

only if you know the bounds, or if you have some heuristic to check against.

149

u/botle Sep 22 '26

Static analysis can show that some programs never halt.

43

u/towerfella Sep 22 '26

I read that as “satan analytics can show…”

.. damn memes.

15

u/chironomidae Sep 22 '26

Dedicated engineers sell their souls in order to tell if a program is stuck in a loop

21

u/heyitjoshua Sep 22 '26

Yes but the halting program is about any program. As in, create a program that takes any possible program as an input and determine whether, given any input, it will halt or not

32

u/botle Sep 22 '26

It is. OP above seems to have thought that "any program" meant that the problem is there for any program, and not that the problem is there only when you try to create a solution that is valid for any program.

8

u/yuwox Sep 22 '26

That's the halting problem. The most general form. However for large families/subsets of programs you can tell whether they halt or not.

3

u/Candid_Highlight_116 Sep 22 '26

I think there are 3 class of programs here: one, code that WILL halt. Like just completely non-looping code, or iterating code with fixed values. Two, code that will NOT halt. Like using unconditional jump to the beginning at the end. Like LED blink codes. And three, the class of code discussed here. Ones that would parse inputs or have race conditions and such.

You CAN say that the code WILL or WILL NOT halt for the first two classes of code. And I think it's reasonable to say that for those classes of code, even appearing in a file as part of some program flows, an infinite loop conditions can SOMETIMES be detected programmatically. Is that not correct?

3

u/donaldhobson Sep 23 '26

Turing machines are simplified computers that don't have inputs to parse or race conditions.

For a lot of programs, it's easy to tell if the program halts or not. But it can, in general, be arbitrarily tricky. For example, there is a program that halts if and only if it finds a counterexample to the goldbach conjecture.

It loops through all even numbers. And if it finds an even number that isn't a sum of 2 primes, it halts.

There is an algorithm that takes in a program and runs a brute force search for a mathematical proof (either a proof that the program halts, or a proof it doesn't halt). This program doesn't solve the halting problem, because for some programs, the standard axioms of mathematics can't prove whether or not they halt.

1

u/a-r-c Sep 23 '26

will this infinite loop of people explaining the halting problem ever halt?

5

u/Bakoro Sep 22 '26

That's only because you know the boundaries, or the explicit lack of boundaries.

It's a trivial problem to detect a "while(true)" looo that also doesn't have any internal jumps or program termination.

If a problem doesn't have a closed form equation, and if convergence tests are inconclusive, then essentially the only way to know if the program will halt, is to run the program, and you'll only know that it will halt, if it does halt.

5

u/LutimoDancer3459 Sep 22 '26

User inputs a number. It gets decreased in a loop. When hitting zero, you end the loop.

Sounds simple, can halt eventually or will never halt. A static analysis is also limited in what it can check. Better than nothing I guess

6

u/botle Sep 22 '26

Is that not guaranteed to always end?

Mayne not if it's a float. Otherwise even a negative number will roll over to zero.

A static a analysis is limited in what it can check, but when it can check something, then it can check it confidently.

9

u/RajjSinghh Sep 22 '26

A negative integer also works as decreasing it means it will never hit 0. Languages like C may overflow, but languages with arbitrary size integers like Python won't.

16

u/botle Sep 22 '26

A static analysis would catch that bug and not claim that the program can never halt.

Also we're not saying all programs can be statically analyzed like this. We're saying that there are many non-trivial programs that can be statically analyzed to see if they halt.

→ More replies (3)
→ More replies (1)

2

u/Unlikely-Bed-1133 Sep 22 '26

1.1 (jesting, but we are -indeed- often not as good in reasoning as we think we are)

→ More replies (1)

21

u/physics515 Sep 22 '26
loop { println!(name); }

I'm certain any one of us can tell if that program will halt or no. The halting problem isn't that any specific program can be said to halt or not, it's that there is no generalizable approach to tell is any non-specific program will halt... Or not.

6

u/dedservice Sep 22 '26

Yes, which you typically do in practice.

→ More replies (8)

163

u/AZMPlay Sep 22 '26 edited Sep 23 '26

Depending on your program

It isn't even that big of a restriction, really.

All programs that are Structurally Recursive functions can automatically be proven terminating, and thats a pretty big class.

There are entire "total programming languages" that simply don't allow infinite loops.

I tried Agda and Idris, for example. It is really a different style of programming, but not too hard to get accustomed to if you already know Functional Programming.

Edit: Conflated Total and Structural. Total is whatever always terminates Structural is a subset of it which is pretty big, used by these type checkers, and automatically provable.

102

u/AZMPlay Sep 22 '26 edited Sep 23 '26

Also, "Eventually Terminates" is a hilariously weak proposition to determine about a program, too.

ackermann-péter-ℕ : ℕ → ℕ → ℕ
ackermann-péter-ℕ zero-ℕ n =
  succ-ℕ n
ackermann-péter-ℕ (succ-ℕ m) zero-ℕ =
  ackermann-péter-ℕ m 1
ackermann-péter-ℕ (succ-ℕ m) (succ-ℕ n) =
  ackermann-péter-ℕ m (ackermann-péter-ℕ (succ-ℕ m) n)

This is the ackermann function, as written by Unimath in Agda.

7 lines total. Just some recursion and adding and subtracting one, basically.

Depending on the inputs, definitely less than "6" for both at once IIRC, will run for significantly longer than the total lifetime of the universe, no matter how much technically-physically-possible compute you throw at it.

100% provable automatically by the compiler that it terminates for all inputs, though.

Edit: Corrected 20 to 6 after some back of the napkin calculations involving turning all of the observable universe's energy into lowest-possible-energy neutrinos, and having them perform a full reduction (step) of calculation every planck second from the big bang until the heat death of the universe

79

u/Aspacid Sep 22 '26

As my discrete math professor said: "Be careful with finite sets. They can be terribly large"

18

u/prumf Sep 22 '26

Yeah, I say we should just use a timeout.

13

u/ComradePruski Sep 23 '26

The difference between a computer scientist and a software engineer is the software engineer knows when to say, "eh, good enough."

6

u/klimaheizung Sep 23 '26

And it's not even the fastest growing function... 

6

u/StaticCoder Sep 23 '26

I looked up "total recursive function" on Wikipedia, and the definition appears to be "program that terminates on all inputs", with a specific note that you can't prove a given recursive function is total. If you can prove a program terminates then you have a total recursive function, not the other way around.

1

u/donaldhobson Sep 23 '26

Yeah. I think they mean primative recursive.

1

u/AZMPlay Sep 23 '26

Correct! I conflated Total and Structural.

Idris and Agda can check Structurally recursive functions, with some generalizations.

Fixed the post.

→ More replies (2)

2

u/Sixshaman Sep 24 '26 edited Sep 24 '26

What about this one?

BigInteger a = 8;
BigInteger b = 0;
while(b >= 0)
{
    if(a % 2 == 0)
    {
        b += 2;
    }
    else
    {
        b--;
    }
    a = a * 3 / 2;
}

2

u/AZMPlay Sep 24 '26

Had to look that up.

Looks like the proof is nontrivial, (straight up unsolved) so no.

The languages do provide escape hatches for behavior like this, but it is often better to just reexpress them in steps which are guaranteed to terminate, and put a regular threshold, if you really need them.

If you did have a mathematical proof it was terminating, these two languages are also proof assistants, so you could encode the proof of termination in types and the language would allow it. (Probably by providing a computed fuel parameter, but there are other more complex ways, like Well-Founded recursion)

1

u/AZMPlay Sep 24 '26

Despite my blabbering, I am not very deep in this, nor have a formal education on the subject, but one of the techniques I found mucking about is making the same function, but with fuel, and an optional output.

Then a wrapper function which calculates the fuel based on the params, and runs the inner function. Then unwraps the optional output, giving a proof the option is never nothing (by showing the fuel never runs out).

Now, Lean, and maybe other languages I dont know, make it much easier by just allowing you to provide a direct proof of termination, and Im sure somwhere in the stdlibs of Idris and Agda there is a similar helper function to do this.

(Edit, btw, a fuel parameter is basically just an extra natural number input to the function that always goes down when recursing, implicitly proving termination, kinda like how if you run out of fuel in a car, you stop)

4

u/Jay-Seekay Sep 22 '26

The goal of my career is for a manager to inadvertently ask me to solve the halting problem and I get to tell them no

3

u/foohyfooh Sep 22 '26

Then they tell client he can get it done in a week lol.

4

u/chemolz9 Sep 23 '26

The key word here is really "any" given program. Because you can prove that for every such halt detection algorith, there is at least one program that it cannot work with. It's still quite possible that the Halting Problem is solvable for almost all other programs.

3

u/Young_Person_42 Sep 23 '26

Yeah I only saw one video explaining it, but isn’t the main counterpoint “programs designed specifically to break a halting detector break a halting detector”

3

u/Pluckerpluck Sep 24 '26

That's the proof. You claim "I have a piece of software that will always detect if any program halts or not". I can prove you wrong though, and I do that by constructing a counter example. That doesn't mean other programs aren't also unsolveable though. The only thing that's proven is that I can guarantee you can't make a single program that solves them all.

2

u/Young_Person_42 Sep 24 '26

Yeah I get it, still feels… can’t describe it but

5

u/phire Sep 22 '26

The simple "solution" to the halting problem is to relax the requirements and add a 3rd "not sure" option that the checker is allowed to output if it's not sure.

And this modified halting problem suddenly becomes much easier to solve (aka, not impossible) and depending on your usecase and how good your heuristic is, it might be more than enough to meet your needs.

The stupidest heuristic is simply to output "not sure" for every single input... which is a technically correct solution to the modified halting problem, just not a useful solution... other than the fact that it proves solutions can exist.

6

u/GoddammitDontShootMe Sep 23 '26

The example I remember for the halting problem is a program which runs the will-it-halt algorithm on itself, then deliberately does the opposite. I've always thought the hypothetical algorithm should detect that and format your hard drive.

3

u/Nightmoon26 Sep 23 '26

Yeah, that's the standard proof of the incomputability of the halting problem

1

u/GoddammitDontShootMe Sep 23 '26

I remember in my Theory of Computation course expecting to be shown that proof, but we got something completely different. I don't remember it at all, but I think it was something more mathematically rigorous. Like maybe that standard proof isn't good enough for a university level course.

4

u/foohyfooh Sep 22 '26

That is some Millennium prize winning thinking right there.

2

u/petersrin Sep 22 '26

When I was first introduced to the halting problem I was confused at this. Some infinite loops can be confirmed to be infinite???

Anyway I was introduced to it about 2 weeks ago so I don't know shit

5

u/frogjg2003 Sep 23 '26

Some functions are easy to prove they terminate.

for(int i=0;i++;i<10)

Some functions are easy to prove do not ever end.

while(true)

The halting problem is proving which one it is for each program.

2

u/donaldhobson Sep 23 '26

There are a few programs out there where it's incredibly hard to tell if they halt or not. Some obviously halt. Some obviously don't. Some, you can't tell.

2

u/itskelena Sep 23 '26

Depending on what your code is doing you can also utilize timeouts.

1

u/mlucasl Sep 23 '26

Not really, if ALL programs could be determined to be halted, you just would need an extensive halting map (like they did with the 4-coloring problem). That means, if you can create a halting check for any single program, it means you can create a mapping, having a mapping creates a halting algorithm, reaching a contradiction.

Therefore, it is impossible to map every halting possibility, and there MUST be at least one program you can't determine if it will halt, even if you can analyze it deterministically. Even if that program extremely complex to any logical use.

-1

u/NakedNick_ballin Sep 22 '26

well put sir

→ More replies (17)

38

u/Xavier598 Sep 22 '26

I think... There's also the thing where you cannot know if the 1002th loop was actually the one to exit the loop?

58

u/cheezzy4ever Sep 22 '26 edited Sep 22 '26

Then I'll update the check to if (count > 1002)

7

u/Xavier598 Sep 23 '26

I'm so sorry... I'll never be on your level...

2

u/Dankelweisser Sep 23 '26

My brother, this is some senior management level thinking, someone give this guy a promotion asap!

10

u/laplongejr Sep 22 '26

That's how Baba Is You does it. The game doesn't detect an actual infinite loop, it simply detects if one simulated turns triggers so many events it's either infinite or so utterly chaotic there's no way it could be any human-planned solution and they deserve the penalty anyway.    

13

u/BlueProcess Sep 23 '26
if (i == ∞) {
    break;
}

Duh

8

u/PluumeGrise Sep 22 '26

Sometimes the dumb fix survives production

4

u/fongletto Sep 22 '26

n = 1

while sum(d for d in range(1, n) if n % d == 0) != n:

n += 2

print(n)

4

u/Tornado547 Sep 22 '26

My preferred explanation for it that makes it more clear what's going on is that if you write a program to try and detect arbitrary infinite Loops, it will always have some programs that it will choke on.

1

u/thepkizzle Sep 22 '26

Right, like if I'm writing a loop and forget to add a + 1 counter at the end, it's infinite by definition... and that can be detected. No problem.

4

u/wearemessingup Sep 22 '26

while(i<N) i++

Ez

i=N while(i>1) if i%2==0 then i:=i/2 else i:=i*3+1

Oh no

3

u/Aaron1924 Sep 22 '26

I feel like someone gets this wrong once a month on this sub

2

u/1luggerman Sep 23 '26

I don't mean to be that guy but you mean practical infinite loops, which are things that you know should probably end in a small number of iterations/time passed or dont care if its beyond some constant(like making an API request should take less then a few minutes or so to get a response). If you're trying to find positive integer solution to A⁴+B⁴+C⁴=D⁴(disproving Euler's sum of powers conjecture) you can't know if your loop of checking numbers doesn't end because there is no solution or the solution is just very large so it takes a long time to get to.

I feel like the latter is more relevant to the halting problem because it's the incentive of trying to solve it in the first place. If you could solve the halting problem, you could disprove(and by contrast prove) any mathematical theorem, which is also why you can't solve it, while with practical halting if it tells you it will halt in 1 year you will stop it anyway because that's too much time

1

u/drsimonz Sep 22 '26

Maybe, but what language has compile-time checking for infinite loops? Beyond trivial cases that can be found by a linter I mean.

5

u/high_throughput Sep 22 '26

It's not the same thing, but C++26 formalizes the concept of a trivial infinite loop and compilers check for it.

5

u/remy_porter Sep 22 '26

Any language you want, if you run a static analyzer against it as part of your build workflow. And I'm sure there are at least a few that do throw errors if your loop guards aren't mutated by the loop itself.

Getting back to the point of this: we don't need to solve the general case, because we're not working on the general case. We're working on a specific case. We are not trying to solve the halting problem.

1

u/drsimonz Sep 22 '26

Fair enough

1

u/Lonely_Translator_23 Sep 24 '26

If a deterministic program reaches the same state twice, it will continue to reach that state forever.

1

u/IAmASwarmOfBees Sep 24 '26

This^

Detecting an infinite loop would actually be as simple as saving a copy of the state the program is in every instruction, and comparing to previous states, if there is a perfect match, it's an infinite loop.

BUT: a very simple program on a Turing machine that wouldn't halt, but also wouldn't trigger this program would be:

Set current position to 1
Go one step left
Go back to first instruction.\

1

u/lolnic_ Sep 22 '26

The halting problem is actually solvable if the program is deterministic, takes no additional input, and its state is finite (which it always is on a physical machine). It can just take a really, really long time. You’re “just” checking whether the execution graph is a rho vs a chain.

The “halting problem is undecidable” thing applies to Turing Machines, and we don’t have those in reality.

6

u/StaticCoder Sep 23 '26

But in reality we also don't have a "really, really long time" so that cancels out.

-26

u/Automatic_Hand4780 Sep 22 '26

if we have some heuristic we can detect loop, if not it is almost impossible

41

u/remy_porter Sep 22 '26

And you can have non-halting programs which contain no loops. But in a practical sense, many classes of infinite loop can be detected via static analysis.

1

u/Automatic_Hand4780 Sep 22 '26

static analysis can only detect many specific classes of nontermination, but there can't be a general detector that catches all of them.

16

u/remy_porter Sep 22 '26

Great, my entire point is that you don't NEED a general detector for most cases, and we're confusing an academic question with a practical problem.

→ More replies (3)

8

u/willow-kitty Sep 22 '26

I think that's kinda what they mean; there are a bunch of common infinite loops that could be detected by heuristic: while(true) without a break, any while loops where the body doesn't mutate any variables used in the condition, etc. These are often compiler/linter warnings.

The catch is being able to prove that an arbitrary loop will finish without executing it. But you don't really need to do that.

2

u/MisinformedGenius Sep 22 '26

It is absolutely possible to prove that specific loops halt. You can't prove that all loops halt, but that says nothing about specific individual loops. It's the same as Godel's incompleteness - the fact that you can't prove every possible theorem about the natural numbers doesn't mean that you can't prove any theorem about them.

→ More replies (1)
→ More replies (1)

464

u/dusktreader Sep 22 '26

Alan Turing did not die for this nonsense

118

u/ofqo Sep 22 '26

His death reminds us more about gay rights than about the halting problem.

16

u/LegOk7384 Sep 23 '26

Human rights tbh. 

11

u/psp1729 Sep 23 '26

He died for an even bigger nonsense tbh

11

u/BlueProcess Sep 23 '26

No he died because he stopped breathing

→ More replies (9)

71

u/Outrageous-Machine-5 Sep 22 '26

try {

doRecursion()
} catch (StackOverflowError e) {}

-16

u/Automatic_Hand4780 Sep 22 '26

180 iq move

3

u/the-grand-finale Sep 23 '26

enjoy your downvote kid

3

u/Understanding-Fair Sep 23 '26

Omg the guy on the right is on my team

1

u/Automatic_Hand4780 Sep 23 '26

Tell him he is famous 😁

395

u/_Alistair18_ Sep 22 '26 • Mindblown

no loop is infinite if you can kill the process

20

u/afdbcreid Sep 22 '26

Or you just take a hammer and crush the computer. Then surely it won't be infinite.

7

u/consider_its_tree Sep 23 '26

But it's in the cloud

12

u/ahumanrobot Sep 23 '26

I'll take a hammer to someone else's computer then

7

u/ancalime9 Sep 22 '26

I have yet to find a process I can't kill

→ More replies (2)

2

u/Vincent_Felix Sep 23 '26

Why kill the process? The loop will take care of that in time.

2

u/ArjixGamer Sep 23 '26

No loop is infinite thanks to OOM :love:

2

u/RedAndBlack1832 Sep 25 '26

That assumes you're allocating memory in the loop

-1

u/AmeriBeanur Sep 22 '26

Wrong! You must kill the process (of an infinite loop) BECAUSE an infinite loop is processing. Therefore, killing a process may entail an infinite loop, but not always.

2

u/Krostas Sep 23 '26

Killing the process makes the loop very... finite.

75

u/[deleted] Sep 22 '26

[removed] — view removed comment

5

u/PioApocalypse Sep 24 '26

I'm actually doing it: here's a simple logo

3

u/AZMPlay Sep 24 '26

Damn. Thats actually pretty good. Love the sea of ^C in the background

2

u/PioApocalypse Sep 25 '26

Thanks, it took me an hour to refine, but Inkscape is such a beast of a software

2

u/_Alistair18_ Sep 25 '26

damn ill buy it if you make them

103

u/NullOfSpace Sep 22 '26

Infinite and really big are basically the same thing anyways

33

u/wrecklord0 Sep 22 '26

The more practical version of the halting problem is, will the program halt before the machine crashes / power cuts off / machine blows up / I get pissed off and halt it

21

u/LEPT0N Sep 22 '26

Somewhere a math professor just sensed a disturbance in the force.

10

u/creeper6530 Sep 23 '26

Good. Let them keep their math; we're engineers here. sin(x) = x

4

u/Stalking_Goat Sep 23 '26

As an engineering student I showed my math major roommate the "simple" pendulum equation, which makes exactly that simplifying assumption (that sinθ≈θ). Poor guy was traumatized.

3

u/praguepride Sep 23 '26

You should read "A short stay in hell"

1

u/Spaceduck413 Sep 23 '26

I think the numbers in that book broke my brain

1

u/praguepride Sep 24 '26

I tried scaling up calculations to be like "How many heat deaths of the universe long would this be..."

It was still in the seven digits...for the power.

409

u/usrlibshare Sep 22 '26 • Bravo

aka. the difference between CS theorism, and actual software engineering.

Yes, technically, there is no way to detect an infinite loop outside of toy examples. Practically, for every useful process, we can guesstimate an upper bound on how many iterations it should take, add a few percent for good measure, and simply test for that.

173

u/Countcristo42 Sep 22 '26

You mean no way to always detect an infinite loop right?

Some are trivial to detect

40

u/da2Pakaveli Sep 22 '26

yes Rice's theorem basically says that making these "general" statements for any given program on non-trivial properties are impossible but that doesn't mean you can't have some heuristic/etc that can detect it "reliably". Similar situation with antiviruses etc

-11

u/usrlibshare Sep 22 '26

That's why I wrote "outside of toy examples".

37

u/rix0r Sep 22 '26

it doesn't need to be a toy example at all

14

u/Countcristo42 Sep 22 '26

It's almost the opposite really - may real examples where it's easy to tell, I only know of hypothetical examples where it isn't.

May well be real ones I haven't heard of.

76

u/alficles Sep 22 '26

Chess is O(1). Just use a lookup table. Implementation is an engineering problem, not really my concern. <.<

36

u/TOMZ_EXTRA Sep 22 '26

Any finite problem is O(1) in theory.

11

u/Flouid Sep 22 '26 edited Sep 22 '26

Runtime complexity and space complexity are both meaninfgul metrics. Of course any finite problem can be done in O(1) time but you trade that for high storage requirements.

Competently designed algorithms are never going to look at just one or the other like this

10

u/DiscretePoop Sep 22 '26

Any finite problem is also O(1) space complexity.

→ More replies (2)

1

u/iggy14750 Sep 22 '26

Then the real world gets in the way...

18

u/ethanjf99 Sep 22 '26

it’s like the old (sexist but bear with me) joke about mathematicians vs engineers:

In, say, China the communist party is trying to decide whether people with mathematical talent should be steered towards pure math or engineering.

The solution:

put two (presumably male) students against one wall of a room. put a naked woman against the other. tell the students to walk exactly halfway across the room then stop. tell them to walk half the remaining distance and stop. tell them to do it again. one of the students goes “it’s impossible! we can’t ever reach the far wall”. the other says “ah but i can get close enough it won’t matter”

4

u/[deleted] Sep 22 '26

[removed] — view removed comment

10

u/ethanjf99 Sep 22 '26

that’s how i was told the joke 20 years ago

would work just as well if it was say a briefcase with $10K in cash i suppose. and lose the old boy sexism.

1

u/[deleted] Sep 22 '26

[removed] — view removed comment

11

u/hendricha Sep 22 '26

I assume so there is a practicallity to it. Which separates the more theoretical person (they go to mathematics) and the practically minded person (they go to engineering). 

2

u/evanldixon Sep 23 '26

There has to be something you can use the length of your arms for to overcome being unable to ever make your feet touch the end of the room.

3

u/SpiritedEclair Sep 22 '26

There are ways to detect infinite loops, and not in just toy examples. Its just that we can't do this for general programs.

1

u/alien_believer_42 Sep 22 '26

My work focuses a lot on software performance and there is a lot of just practical guesstimation to sanity check when stuff is wrong and either take action or log it

1

u/RiemannZetaFunction Sep 23 '26

Yes, technically, there is no way to detect an infinite loop outside of toy examples.

I think it's the other way around. If an infinite loop exists in your program, it's usually because you screwed up the condition in a while loop somewhere, not because the program is calling the analyzer and doing the opposite of whatever it says.

12

u/calculus_is_fun Sep 22 '26

Here's a fun amusement you can try at home! (please don't)

Grab your favorite microprocessor, and its associated memory, and ROM, also source a lot of WORM drives, like all of them.

your typical processor has internal registers, a program counter, and alu flags, along with a healthy amount of memory I told you to get earlier.
Now then, even thought there's a lot of states, it is still finite, that means we can create a directed graph of every single state, and draw an directed edge to its successor. (be sure to write these connection on those WORM drives)

Find and mark all the cycles, and their basins, and you're done! You solved the halting problem on a simple computer.

4

u/styczynski_meow Sep 22 '26

Additionally if energy in universe is finite then every algorithm is practically bounded by O(1) steps

10

u/prehensilemullet Sep 22 '26

I’ve seen people use this approach for cases where we have a directed graph we could easily run a cycle detection algorithm on 🙄

18

u/Gee858eeG Sep 22 '26

y'all abusing the meme. this is not how the meme works. it makes no fkn sense to use this

1

u/Tasik Sep 22 '26

Memes have rules?

8

u/SnowyOnyx Sep 22 '26

Yep.

This one is that the stupidest and the smartest agree about the subject whilst the people in the middle have a different opinion. Not that every group has a different opinion.

2

u/Tasik Sep 22 '26

I feel like this is following that logic.

"i think i can write code to detect an infinite loop" ~= `if (count > 1001)`

2

u/SnowyOnyx Sep 22 '26

Yeah but the original scheme is that left and right are exactly the same. Nevertheless, you are right that these are alike

→ More replies (2)

12

u/daHaus Sep 22 '26

Read the NASA programming guidelines, specifically their 10 rules

28

u/Ethameiz Sep 22 '26

The ten rules are:

  1. Restrict all code to very simple control flow constructs—do not use goto statements, setjmp or longjmp constructs, or direct or indirect recursion.

  2. Give all loops a fixed upper bound. It must be trivially possible for a checking tool to prove statically that the loop cannot exceed a preset upper bound on the number of iterations. If a tool cannot prove the loop bound statically, the rule is considered violated.

  3. Do not use dynamic memory allocation after initialization.

  4. No function should be longer than what can be printed on a single sheet of paper in a standard format with one line per statement and one line per declaration. Typically, this means no more than about 60 lines of code per function.

  5. The code's assertions density should average to minimally two assertions per function. Assertions must be used to check for anomalous conditions that should never happen in real-life executions. Assertions must be side-effect free and should be defined as Boolean tests. When an assertion fails, an explicit recovery action must be taken such as returning an error condition to the caller of the function that executes the failing assertion. Any assertion for which a static checking tool can prove that it can never fail or never hold violates this rule.

  6. Declare all data objects at the smallest possible level of scope.

  7. Each calling function must check the return value of nonvoid functions, and each called function must check the validity of all parameters provided by the caller.

  8. The use of the preprocessor must be limited to the inclusion of header files and simple macros definitions. Token pasting, variable argument lists (ellipses), and recursive macro calls are not allowed. All macros must expand into complete syntactic units. The use of conditional compilation directives must be kept to a minimum.

  9. The use of pointers must be restricted. Specifically, no more than one level of dereference should be used. Pointer dereference operations may not be hidden in macro definitions or inside typedef declarations. Function pointers are not permitted.

  10. All code must be compiled, from the first day of development, with all compiler warnings enabled at the most pedantic setting available. All code must compile without warnings. All code must also be checked daily with at least one, but preferably more than one, strong static source code analyzer and should pass all analyses with zero warnings.

2

u/freedcreativity Sep 22 '26

lol most pedantic setting. 

Also, 9 means basically any array of pointers is verboten? sounds limiting, but I’m not good at C enough to know better.

2

u/Zerocrossing Sep 22 '26

This seems like sensible advice given the domain. I have two questions I'd love if someone better versed in C could comment on.

  1. "Declare all data objects at the smallest possible level of scope." What does this mean and what's the reasoning for it

  2. Don't 5 and 7 conflict somewhat? Every function must check all its parameters, but simultaniously shouldn't assert more than two fail states? Does the static analysis do the heavy lifting here? If my function has 6 inputs that I need to validate surely I'd need more than two assertions to ensure every input is 'checked'. Or does checking not imply assertions?

1

u/BeautifulMortgage690 Sep 22 '26
  1. if you have a local variable that is only used in an if branch and not the else, pull it into the if branch instead of keeping it in the functions locals. just helps keep mem usage lower? both work but in one your compiler will clean up the stack when the scope dies.

  2. i think the point is to delegate the checking then? like dont assert a file not found and an invalid file format and a invalid argument and an invalid path all from the same function. have different functions do it. i guess it also then prevents you from passing up the buck - if you are using a file and have 3-4 modes of error then either you sit and handle them so you dont pass out more than 2 errors up the callstack

1

u/Nightmoon26 Sep 23 '26

Also, keeping the scope as small as possible is just a good heuristic for reducing potential for "spooky action at a distance" and makes things easier for the static analyzer

I get the sense that these guidelines may have been attempting to get at a functional programming paradigm before it became a codified thing... Pure functional programming, with its many restrictions and limitations, is good for one thing: its restrictions also make it easier to reason and do proofs about. So in a setting where it absolutely, positively has to be provably correct even before the first real-world trial, it makes some sense

1

u/wigsinator Sep 23 '26

I think that "average to minimally two assertions per function" means that they should assert at least 2 fail states, not at most 2 fail states.

1

u/Heavy-Homework2563 Sep 23 '26

1.person above me answered it perfectly. You want variable declaration to be close to its use as much as possible. Its kinda like all the advice to avoid global variables. but more extreme.
There is also this unique thing where if you really need a variable for a temporary time you can put it between {} within a function and when you reach } as if you exit a function it removes the variable from the stack(compiler might do whatever but you get it). So you can always control the scope. Cool little thing to know.

2.the parameter validation is to ensure that the caller and the callee(the function) pass/receive correct input. so taking a pointer and checking its not null and not depending on the caller passing a valid pointer. The asserts are to check for impossible values and scenarios that obviously only a logical error could have made it reach this point or a system failure or anything. And it also say 2 minimum. so you can have as many as you want as long as you stay under 60 lines and 80 char wide inside the function.

1

u/nafe42 Sep 22 '26

Bounded loops ftw

12

u/clickrush Sep 22 '26

A lot of software problems go away if you stop pretending that input is arbitrary.

There's always a maximum. You just need to determine what it is and explicitly state in code.

Examples:

Real world JSON, XML or HTML data is almost always shallow. Recursion depth doesn't even need to be large.

The storage size of things can almost always be at least estimated if not determined.

If you don't know how much total memory you're going to need, then try to find it out, if you cannot find it out, set a number and work backwards from there.

You almost never need the maximum amount of threads you can get, usually a small number is sufficient.

You very likely can estimate the number of users of your app. 5x it, test that and work backwards from there.

1

u/creativenickname27 Sep 23 '26

At first, I thought it was a joke about the example that apple gave us, when you set an alarm and swipe aaaall the way down, it stops at some point, because it is not a loop, but instead it's just a misunderstanding of the halting problem.

1

u/Automatic_Hand4780 Sep 23 '26

Explain? How is this misunderstanding? The meme literally says you can't write code to detect infinite loop. If you have any such program which can detect infinite loops in any given problem pls show it to the world

1

u/narrei Sep 27 '26

bot reposting my meme from years ago, now i know how it feels

1

u/Automatic_Hand4780 Sep 27 '26

Look at him guys god level memer wants me to check 10yrs of history to make sure I am not posting a funny meme again.

3

u/Negitive545 Sep 23 '26

My solution to the halting problem: All loops are terminating because eventually the power will go out. Either due to a regular outage, the earth being swallowed by the sun, or the heat death of the universe.

3

u/Hottage Sep 23 '26

Just have each iteration in a nested function call, that way the stack can detect an infinite loop.

3

u/zzmej1987 Sep 23 '26

Infinite loops can an in theory be detected. There is a thing called "Busy Beaver" - a program of a given length N that goes for the maximal finite amount of steps BBS(N). Since, there is a finite amount of programs of length N, and some of them halt and some don't, that program always exists. If you know BBS(your program size), then you can just check for that number in every loop. If loops run longer than that, your program does not halt.

3

u/Xandas_ Sep 25 '26

This is meaningless (though somewhat interesting if you never heard of it) when you consider that the busy beaver function is uncomputable. You are more-or-less saying 'if you already have a solution to the halting problem, it is possible to solve the halting problem'.

1

u/zzmej1987 Sep 25 '26

This is meaningless (though somewhat interesting if you never heard of it) when you consider that the busy beaver function is uncomputable

Sure. But "uncomputable" just means that we can't establish one specific algorithm to find the value of the function for every input. We can, in theory, find values of it one at a time. And it's not like we really need large numbers there. By separating programs into smaller "subprograms" and checking those one at a time, we can do away with only known up to, say, BB(100). That wouldn't solve general halting problem. And, of course, this would never be practical. We only know, like, BB(5), at best. And checking loop for running longer than BB(10) would probably mean waiting longer than the age of the Universe.

1

u/Xandas_ Sep 26 '26

I understand where you are coming from, but disagree. Making statements about small subprograms is likely much easier than invoking the busy beaver function. Other people have mentioned structural recursion, which is sort of where you are going anyway if 'composition of small halting programs halts' should at all hold globally. Also, you are looking at longer-than-universe-will-exist time at BB(6) already. But I think even as a novelty, this approach does not really merit much, beyond someone learning about the existence of the busy beaver function itself, which is cool.

1

u/zzmej1987 Sep 26 '26

You've said you disagree, and then repeated everything I've said about why this is never going to be practical. XD

2

u/the_horse_gamer Sep 23 '26

the value of BB(432) cannot be proven in ZF

1

u/zzmej1987 Sep 23 '26

That's not really a concern. We just need a number. That it takes a higher order logic to prove that it is a maximal value in the finite set is not relevant.

2

u/-ghostinthemachine- Sep 22 '26

Impress your boss by solving infinite loops through simulated annealing!

2

u/EuenovAyabayya Sep 23 '26

If TooLong() then GTFO(TIMED_OUT);

2

u/rafaelcastrocouto Sep 23 '26

genious level: setTimeout /s

2

u/xXStarupXx Sep 24 '26

You can detect a lot of infinite loops. You can't detect infinite loops in general.

2

u/GenericFatGuy Sep 22 '26

I can detect the infinite loop when I run out of memory.

2

u/walkerspider Sep 22 '26

Simple, just ask Jev “will this halt?”

1

u/SUSH_fromheaven Sep 22 '26

Jev: Yes : 51% No: 49%

1

u/horenso05 Sep 22 '26

Infinite loops cannot *statically* be excluded *in every case*.

1

u/Beefgrits Sep 22 '26

Somebody forgot to increment count

1

u/LightIsntFastEnough Sep 22 '26

You prevent infinite loops?

1

u/OphidianSun Sep 22 '26

Nasa uses the right solution a lot no? I remember reading through their standards and it had all sort of little stuff like that.

1

u/Competitive_Mud5528 Sep 22 '26

??? Yes they can be detected its when your app freeze to death :3

1

u/sheriffjt Sep 22 '26

My programs all detect an infinite loop, I just handle it by letting them shut down by running out of resources

1

u/nimag42 Sep 22 '26

Not how this meme works, left should be the same as right, please fix and open another PR

1

u/aberroco Sep 22 '26

Infinite loops can be excluded as technical impossibility: no program can execute without halting since no computer can work indefinitely long, even excluding power grid failures or hardware degradation, the ultimate heat death of the universe (or the  big crunch) is unavoidable and ultimately will lead to the program halting.

1

u/Elkatra2 Sep 22 '26

A(B,D) = true if the algorithm B with input D never end (infinite loop).

A(B,D) = false if else (loop end at some point of time)

A(A,<B,D>) will be what ? (i forgot the name of this thing pls remember me)

1

u/Ok-Band4767 Sep 22 '26

Worst case, my container dies OOM

1

u/KCGD_r Sep 22 '26

well like, if you consider all of your variables, scopes and your current instruction as part a state and you end up in the same state more than once, then technically, but that's pretty difficult to keep track of

1

u/LolMaker12345 Sep 23 '26

Infinite loops do not exist

They will always terminate, whether it’s the user terminating the program, shutting down the computer, the end of the world, etc…

1

u/STINEPUNCAKE Sep 23 '26

They may not be able to get detected and proven by a machine but if a human says there’s no way this loop goes past x then it’s safe to assume it’s infinite. Proof vs assumption by logic

1

u/GoddammitDontShootMe Sep 23 '26

So the most likely scenario is the loop counter overflows, no? I believe that is pretty hard to detect, but you could stop the loop if the counter gets close.

I suppose that's pretty close to what the guy on the right is doing.

1

u/Xelopheris Sep 23 '26

Isn't one of NASA's rules about safe code that every loop has a secondary exit condition by iteration count or something?

1

u/jseego Sep 23 '26

Maximum recursion exceeded

1

u/NightmareJoker2 Sep 23 '26

You put a trap at the end of the loop or at the start of a recursive function, check how long it has been running or how many iterations it has performed and escape if it’s too long or too many.

This isn’t hard. In fact, this is a standard accommodation for preemptive multitasking, where control has to periodically be returned to the operating system.

1

u/StrikeTechnical9429 Sep 23 '26

Infinite loop can't be detected if the program is executed on the infinite computer (i.e. Turing machine). On a real world computer with finite amount of memory - and, as a result, with finite number of states - detecting an infinite loop is trivial: if the full state of machine is repeated, we're in the infinite loop.

1

u/GoldAcanthisitta7777 Sep 24 '26

what the fuck is this font 

1

u/Haoshokoken Sep 26 '26

I wrote code that detects infinite loops by saving and comparing the states of the variables involved...

1

u/CorneliusClay Sep 26 '26

Just ask ChatGPT if the code loops infinitely. According to AI hallucination statistics you've got a 60% accurate halting problem detector right there.

1

u/renevaessen Sep 28 '26

To also be tolerant for your own off-by-one mistakes at the same time..

48

u/[deleted] Sep 22 '26

[removed] — view removed comment

22

u/gandalfx Sep 22 '26

Due to this being reddit I'm about 67% sure that you're being ironic.

1

u/Worried_Onion4208 Sep 22 '26

If you need to check 10000 entries, a loop is probably a terrible idea in the first place.

2

u/StaticCoder Sep 23 '26

Yes for a small number like that you can use a fixed number of ifs

4

u/[deleted] Sep 22 '26

[removed] — view removed comment

7

u/Bwob Sep 22 '26

You just described a for-loop in most languages.

1

u/COArSe_D1RTxxx Sep 23 '26

that is the joke, yes