Struct Json封送处理导致堆栈溢出

Struct Json封送处理导致堆栈溢出

问题描述:

Problem

When I use the NewChild() function in my code and than afterwards marshal the "Report" Struct to JSON I get a Stack Overflow (goroutine stack exceeds 1000000000-byte limit)

After researching I found out that it should have to do something with infinite recursion, but I don't have a clue why my code should have that.

Code

type Report struct{
    TestSuites []ReportElement
    Tests int
    Success int
    Failed int
    Root *ReportElement
    CurrentElement *ReportElement `json:"-"`
}

type ReportElement struct{
    Success bool
    Time bool
    LogStorage []string
    Childs []ReportElement
    Parent *ReportElement
}

func (r *Report) NewChild(){
    newElem := ReportElement{}
    newElem.Parent = r.CurrentElement
    newElem.Childs = make([]ReportElement,0)

    newChilds := append(r.CurrentElement.Childs,newElem)
    r.CurrentElement.Childs = newChilds

    r.CurrentElement = &newElem
}


func TestReporterStackOverflow(t *testing.T) {
    report := NewReport()
    report.NewChild()

    jsonReport,err := json.MarshalIndent(report,""," ")
    if err != nil{
        t.Fatal(err)
    }

    t.Log(jsonReport)
}

Ideas

Actually I am not sure if it has to do something with my code as the stacktrace leads to "/usr/local/go/src/encoding/json/encode.go".

Thanks a lot for your help!

You have multiple infinite loops due to the parent/child pointers. Each parent points to its children, which point back to their parent. Note that when deserialized, multiple pointers to the same object will end up being multiple separate objects, which likely is not what you want.