Skip to content

Commit 0098366

Browse files
committed
Tensor: check the gcHandle against Zero before deallocating it
1 parent de0ee59 commit 0098366

File tree

1 file changed

+3
-4
lines changed

1 file changed

+3
-4
lines changed

src/TensorFlowNET.Core/Tensors/Tensor.Creation.cs

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -564,7 +564,7 @@ public Tensor(Operation op, int value_index, TF_DataType dtype)
564564
_id = ops.uid();
565565
}
566566

567-
private bool _isPinnedArray = false;
567+
private bool _isPinnedArray => _deallocatorArgs.gc_handle != IntPtr.Zero;
568568

569569
/// <summary>
570570
/// Creates a new tensor from the given array without copying memory. The array is pinned down and the pointer passed on.
@@ -620,12 +620,11 @@ protected unsafe IntPtr CreateTensorWithoutCopying(TF_DataType dt, long[] shape,
620620

621621
// get a handle to the pinned array which we will pass on to the tensor computation engine to use
622622
var gcHandle = GCHandle.Alloc(data, GCHandleType.Pinned);
623-
_isPinnedArray = true;
624623
_deallocatorArgs = new DeallocatorArgs() { gc_handle = GCHandle.ToIntPtr(gcHandle) };
625624
// Free the original buffer and set flag
626625
Deallocator deallocator = (IntPtr ptr, IntPtr len, ref DeallocatorArgs args) =>
627626
{
628-
if (args.deallocator_called)
627+
if (args.deallocator_called || args.gc_handle==IntPtr.Zero)
629628
return;
630629
// note: since the ptr given to tensorflow is just the addr of the pinned object we can not directly free it! we need to free the gcHandle instead
631630
GCHandle.FromIntPtr(args.gc_handle).Free();
@@ -638,6 +637,6 @@ protected unsafe IntPtr CreateTensorWithoutCopying(TF_DataType dt, long[] shape,
638637
return TF_NewTensor(dt, shape, shape.Length, gcHandle.AddrOfPinnedObject() + start * element_size, (UIntPtr)(count * element_size), deallocator, ref _deallocatorArgs);
639638
}
640639

641-
private DeallocatorArgs _deallocatorArgs = new DeallocatorArgs();
640+
private DeallocatorArgs _deallocatorArgs = new DeallocatorArgs() { gc_handle = IntPtr.Zero };
642641
}
643642
}

0 commit comments

Comments
 (0)