8000 Reference looping causes recursion to fail to terminate, resulting in stack overflow · Issue #72 · kr/pretty · GitHub
[go: up one dir, main page]

Skip to content

Reference looping causes recursion to fail to terminate, resulting in stack overflow #72

Open

Description

package main

import (
"fmt"

"github.com/kr/pretty"

)

func main() {
type MyStruct struct {
S []MyStruct
str string
}

var s MyStruct
for i := 1; i <= 3; i++ {
	s.S = append(s.S, MyStruct{})
}

slice2 := s.S
slice2 = append(slice2, MyStruct{str: "测试字符串"})
s.S[0].S = slice2

fmt.Printf("s.S:%v\n", pretty.Formatter(s.S))

}

it will fatal error: stack overflow

Activity

  1. cocolato commented on Apr 27, 2021

    @cocolato

    Infinite recursion can also be triggered by self-referential data structures in "fmt" pkg, such as a slice that contains itself as an element, if that type has a String method. Such pathologies are rare, however, and the package does not protect against them.

  2. kr commented on Apr 27, 2021

    @kr
    Owner

    It's true that fmt doesn't try to protect against cyclic data structures, but I think it's reasonable for pretty to be more defensive and to do something about it.

    Maybe we should have a limit on depth of traversal.

    If so, I guess there should also be a way for the caller to adjust the limit in cases where that's necessary. For example, maybe the default limit is 1000, and most callers never hit it. But if you have a cycle, it will prevent a crash. If you have a deeply nested non-cyclic structure and you want to print all of it, you can increase the limit. Or if you're in a resource-constrained environment, you can lower the limit.

    But hopefully almost everyone would never have to adjust the limit or even know it exists.

  3. added a commit that references this issue on Jul 4, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions

      0