I have a code block that queries AD and retrive the results and write to a channel.
func GetFromAD(connect *ldap.Conn, ADBaseDN, ADFilter string, ADAttribute []string, ADPage uint32) *[]ADElement {
searchRequest := ldap.NewSearchRequest(ADBaseDN, ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false, ADFilter, ADAttribute, nil)
sr, err := connect.SearchWithPaging(searchRequest, ADPage)
CheckForError(err)
fmt.Println(len(sr.Entries))
ADElements := []ADElement{}
for _, entry := range sr.Entries{
NewADEntity := new(ADElement) //struct
NewADEntity.DN = entry.DN
for _, attrib := range entry.Attributes {
NewADEntity.attributes = append(NewADEntity.attributes, keyvalue{attrib.Name: attrib.Values})
}
ADElements = append(ADElements, *NewADEntity)
}
return &ADElements
}
The above function returns a pointer to []ADElements
.
And in my initialrun
function, I call this function like
ADElements := GetFromAD(connectAD, ADBaseDN, ADFilter, ADAttribute, uint32(ADPage))
fmt.Println(reflect.TypeOf(ADElements))
ADElementsChan <- ADElements
And the output says
*[]somemodules.ADElement
as the output of reflect.TypeOf
.
My doubt here is,
since ADElements := []ADElement{}
defined in GetFromAD()
is a local variable, it must be allocated in the stack, and when GetFromAD()
exits, contents of the stack must be destroyed, and further references to GetFromAD()
must be pointing to invalid memory references, whereas I still am getting the exact number of elements returned by GetFromAD()
without any segfault. How is this working? Is it safe to do it this way?