How come Go doesn't have stackoverflows

后端 未结 5 2166
野的像风
野的像风 2021-02-01 19:51

I read in this presentation http://golang.org/doc/ExpressivenessOfGo.pdf page 42:

Safe

- no stack overflows

Ho

5条回答
  •  你的背包
    2021-02-01 20:09

    I think what they are referring to here is that access to arrays is always checked against the actual length of the array, thus disabling one of the most common ways by which C programs crash accidentally or are crashed maliciously.

    For example:

    package main
    
    func main() {
        var a [10]int
    
        for i:= 0; i < 100; i++ {
            a[i] = i
        }
    }
    

    will panic with a runtime error when it tries to update the non-existent 11th element of the array. C would scribble over the heap, and probably also crash but in an uncontrolled way. Every array knows its length. In some cases there will be scope for the compiler to optimize out the checks if it can prove they are not necessary. (Or a sufficiently smart compiler could perhaps statically detect a problem in this function.)

    Many of the other answers are talking about the memory layout of the stack but this is really not relevant: you can have heap overflow attacks too.

    Basically Go's pointers should always be typesafe, with arrays and other types, unless you specifically use the unsafe package.

提交回复
热议问题