feat(free C pointer): added 'defer C.free(unsafe.Pointer(ptr))' to all missing. Except for CMalloc func and Nll func

This commit is contained in:
sugarme 2020-06-17 16:45:59 +10:00
parent 20f338014d
commit 5f7aec5061
5 changed files with 6 additions and 4 deletions

View File

@ -66,9 +66,6 @@ func runLinear() {
* bs.ZeroGrad()
* loss.MustBackward()
*
* // TODO: why `loss` need to print out to get updated?
* fmt.Printf("loss (epoch %v): %v\n", epoch, loss.MustToString(0))
*
* ts.NoGrad(func() {
* ws.MustAdd_(ws.MustGrad().MustMul1(ts.FloatScalar(-1.0)))
* bs.MustAdd_(bs.MustGrad().MustMul1(ts.FloatScalar(-1.0)))

View File

@ -221,6 +221,7 @@ func AtSaveMulti(tensors []Ctensor, tensor_names []string, ntensors int, filenam
cpointerSize := 4
cnamesPtr := (*[1 << 30]**C.char)(C.malloc(C.size_t(cpointerSize * len(tensor_names))))
defer C.free(unsafe.Pointer(cnamesPtr))
for i := 0; i < len(tensor_names); i++ {
cname := C.CString(tensor_names[i])
cnamesPtr[i] = &cname

View File

@ -583,6 +583,8 @@ func (ts Tensor) MustLogSoftmax(dim int64, dtype int32) (retVal Tensor) {
func (ts Tensor) NllLoss(target Tensor) (retVal Tensor, err error) {
ptr := (*lib.Ctensor)(unsafe.Pointer(C.malloc(0)))
// NOTE: uncomment this causes panic
// defer C.free(unsafe.Pointer(ptr))
weight := NewTensor()

View File

@ -466,7 +466,7 @@ func RunBackward(tensors []Tensor, inputs []Tensor, keepGraphB bool, createGraph
// TODO: Are they allocated continouslly???
for i := 0; i < len(inputs); i++ {
outputPtr := (*lib.Ctensor)(unsafe.Pointer(C.malloc(0)))
// defer C.free(unsafe.Pointer(outputPtr))
defer C.free(unsafe.Pointer(outputPtr))
outputsPtr = append(outputsPtr, outputPtr)
}

View File

@ -53,6 +53,8 @@ func init() {
func CMalloc(nbytes int) (dataPtr unsafe.Pointer, buf *bytes.Buffer) {
dataPtr = C.malloc(C.size_t(nbytes))
// NOTE: uncomment this cause panic!
// defer C.free(unsafe.Pointer(dataPtr))
// Recall: 1 << 30 = 1 * 2 * 30
// Ref. See more at https://stackoverflow.com/questions/48756732