lidavidm commented on code in PR #33902:
URL: https://github.com/apache/arrow/pull/33902#discussion_r1090877202


##########
go/arrow/memory/mallocator/mallocator.go:
##########
@@ -0,0 +1,97 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//go:build cgo
+
+package mallocator
+
+// #include <stdlib.h>
+// #include <string.h>
+//
+// void* realloc_and_initialize(void* ptr, size_t old_len, size_t new_len) {
+//   void* new_ptr = realloc(ptr, new_len);
+//   if (new_ptr && new_len > old_len) {
+//     memset(new_ptr + old_len, 0, new_len - old_len);
+//   }
+//   return new_ptr;
+// }
+import "C"
+
+import (
+       "reflect"
+       "sync/atomic"
+       "unsafe"
+
+       "github.com/apache/arrow/go/v11/arrow/memory"
+)
+
+type Mallocator struct {
+       allocatedBytes uint64
+}
+
+func (alloc *Mallocator) Allocate(size int) []byte {
+       // Use calloc to zero-initialize memory.
+       // > ...the current implementation may sometimes cause a runtime error 
if the
+       // > contents of the C memory appear to be a Go pointer. Therefore, 
avoid
+       // > passing uninitialized C memory to Go code if the Go code is going 
to store
+       // > pointer values in it. Zero out the memory in C before passing it 
to Go.
+       if size < 0 {
+               panic("mallocator: negative size")
+       }
+       ptr := C.calloc(C.size_t(size), 1)
+       if ptr == nil {
+               panic("mallocator: out of memory")
+       }
+       atomic.AddUint64(&alloc.allocatedBytes, uint64(size))
+       return unsafe.Slice((*byte)(ptr), size)
+}
+
+func (alloc *Mallocator) Free(b []byte) {
+       sh := (*reflect.SliceHeader)(unsafe.Pointer(&b))
+       C.free(unsafe.Pointer(sh.Data))
+       atomic.AddUint64(&alloc.allocatedBytes, ^(uint64(sh.Len) - 1))

Review Comment:
   It's straight from the docs, but yes, this deserves a comment



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscr...@arrow.apache.org

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org

Reply via email to