On Fri, Sep 22, 2017 at 4:58 PM, Remus Clearwater <remus.clearwa...@gmail.com> wrote: >> So, if the reservation scheme breaks down, it is possible that a C pointer >> is allocated, and then freed, and the C allocator releases the memory, >> but the dangling pointer survives, and the Go allocator allocates that >> space, and the C dangling pointer somehow gets into Go, where it is >> treated as a Go pointer. > > How about this piece of code in the play? I think it is possible to happen > just like what you described even the reservation scheme works well, but > it's been used very often in the current cgo implementation and many open > source projects. > >> package main >> /* >> #include <stdlib.h> >> */ >> import "C" >> import ( >> "fmt" >> "os" >> "runtime" >> "unsafe" >> ) >> func main() { >> type BigObject struct { >> arr [1024 * 1024]byte >> } >> goCstring := func(s string) *C.char { >> // C.malloc -> `addr0` >> p := C.malloc(C.size_t(len(s) + 1)) >> pp := (*[1 << 30]byte)(p) >> copy(pp[:], s) >> pp[len(s)] = 0 >> // go has the 1st object:pp reference to `addr0` >> // although slice pp is not been reference-d anymore >> // but it still exist before the runtime.GC() >> return (*C.char)(p) >> } >> { >> s := string(make([]byte, 1024*1024)) >> p := goCstring(s) >> // C.free(`addr0`) >> C.free(unsafe.Pointer(p)) >> } >> // go malloc -> `addr0` again >> // the slice pp now points to valid go memory :) >> { >> b := BigObject{} >> _ = b >> } >> // 1st GC in go >> // go has 2 objects both reference to `addr0` now >> // the Problem: >> // what is the gc's behaviour in this circumstance? >> // could this lead to some unexpected bugs ? >> runtime.GC() >> os.Exit(0) >> } > > >> But that is really no different from any other way that C can create >> an invalid pointer and pass it into Go. If an invalid C pointer gets >> treated as a Go pointer, there is a bug in the program. > > Let's define this Go pointer as `pp`. > > What if the `invalid C pointer been passed into go` accidently has the > same memory address with one or several already exist go objects (some > objects like channel, mutex or self defined struct, etc). Could it be > possible > to lead some disasters to occur even if `pp` isn't been referenced anymore?
How? You're clearly worried about something, but what is it that you are worried about? If a pointer is not referenced, why would it cause trouble? Ian -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/d/optout.