Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
ghost opened this issue Feb 6, 2021 · 2 comments

Comments

@ghost
Copy link

ghost commented Feb 6, 2021

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

@cocolato
Copy link

cocolato commented Apr 27, 2021

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.

@kr
Copy link
Owner

kr commented Apr 27, 2021

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.

zyga pushed a commit to zyga/spread that referenced this issue Jul 4, 2021
Gustavo's fork (github.com/niemeyer/pretty) contains additional fixes on
recursive elements, so that they don't hang the printer. This is tracked
as issue kr/pretty#72

While the extra patches in the fork are nice, they are not essential and
not needing the fork makes packaging easier.

Signed-off-by: Zygmunt Krynicki <zygmunt.krynicki@huawei.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants