0

CGO Wiki: https://github.com/golang/go/wiki/cgo#turning-c-arrays-into-go-slices This explains how to convert the c arrays into go slices (without copying the original data) and it also makes a statement: "It is important to keep in mind that the Go garbage collector will not interact with this data, and that if it is freed from the C side of things, the behavior of any Go code using the slice is nondeterministic."

But my doubt is, after we are done using this slice, how do we free the memory allocated for the slice? the backing C array can be freed by appropriate calls to the C world, but what about the slice? will it be garbage collected?

Also,

slice := (*[1 << 28]C.YourType)(unsafe.Pointer(theCArray))[:length:length]

will this statement allocate a pretty big array and then slice? I mean, will it cause a BIG memory allocation? if so, how and when will that BIG memory be freed? it is also confusing to understand that the slice will be 'backed by the C array'. if the slice is backed by the C array, then why is a BIG array [1<<28] required?

  • `*[1 << 28]C.YourType` is just a type, it does not allocate anything – JimB May 11 '21 at 16:31
  • thanks @JimB. what about the slice variable? will its memory, which is usually like 12 bytes: 4 bytes for pointer 4 bytes for length and 4 bytes for capacity, be Garbage collected? – chetan kumar May 12 '21 at 06:27
  • The slice variable is like any other variable. If you have: `func f() { var i int; ... }` are you worried about the variable `i` being garbage collected? If so, why? – torek May 12 '21 at 06:50
  • @torek indeed, for normal variables this confusion won't be there. but this slice is backed by C memory, which is not touched by the Garbage collector. So, my question is how the life of this slice, which is kind of mixup of C and GO worlds, is handled? – chetan kumar May 12 '21 at 07:11
  • A slice variable consists solely of a slice *header*. The backing array, if there is one, is independent of the header. Separately, if a Go pointer value *p* points to some Go object *O*, object *O* remains alive. If a Go pointer value points to some C object, the C object is never garbage collected in the first place: only Go objects can be GCed. – torek May 12 '21 at 07:49

0 Answers0