Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does apply with too many arguments throw "Maximum call stack size exceeded"?

In Chrome and Node, the following code throws an error:

function noop() {}
var a = new Array(1e6)
// Array[1000000]
noop.apply(null, a)
// Uncaught RangeError: Maximum call stack size exceeded

I understand why it might be a Bad Idea to pass 1 million arguments to a function, but can anyone explain why the error is Maximum call stack size exceeded instead of something more relevant?

(In case this seems frivolous, the original case was Math.max.apply(Math, lotsOfNumbers), which is a not-unreasonable way of getting the max number from an array.)

like image 371
nrabinowitz Avatar asked Feb 16 '17 01:02

nrabinowitz


People also ask

How do I fix error in maximum call stack size exceeded?

The most common source for this error is infinite recursion. You must have a recursive function in your code whose base case is not being met and is, therefore, calling the function again and again until you hit the call stack limit.

What does it mean when maximum call stack size exceeded?

The JavaScript exception "too much recursion" or "Maximum call stack size exceeded" occurs when there are too many function calls, or a function is missing a base case.

What is maximum call size exceeded?

It means that somewhere in your code, you are calling a function which in turn calls another function and so forth, until you hit the call stack limit. This is almost always because of a recursive function with a base case that isn't being met.

What is JavaScript maximum call stack size?

Without any local variables, each function call takes up 48 bytes during the execution, and you are limited to less than 1MB for all local function frames. Each boolean and number variable takes 8 bytes of memory.


1 Answers

Function arguments are put on the stack. You're trying to put a million arguments onto the stack, and that's more than the maximum stack size. So the error message is very relevant to the reason for the error.

like image 67
Barmar Avatar answered Oct 07 '22 18:10

Barmar