memcpy not working when creating new Tensor inside swap #1935
-
I'm experimenting with swaping the content of two tensors. When I create a new tmp tensor inside swap, its content is not overwritten by A after calling memcpy.
prints:
However, when I pass in a tmp tensor as argument, it works:
Prints:
|
Beta Was this translation helpful? Give feedback.
Answered by
soraros
Mar 12, 2024
Replies: 1 comment 3 replies
-
fn swap(A: Tensor[t], B: Tensor[t]):
var tmp = Tensor[t](5)
memcpy(tmp.data(), A.data(), 5)
memcpy(A.data(), B.data(), 5)
memcpy(B.data(), tmp.data(), 5)
_ = tmp There are other ways to write this code. The following is slightly better: from memory.unsafe import DTypePointer
fn swap(A: inout Tensor[t], B: inout Tensor[t]):
var tmp = DTypePointer[t].alloc(5)
memcpy(tmp, A.data(), 5)
memcpy(A.data(), B.data(), 5)
memcpy(B.data(), tmp, 5)
tmp.free() I think the best option is to use
|
Beta Was this translation helpful? Give feedback.
3 replies
Answer selected by
AlienKevin
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
.data()
is unsafe API, andtmp
is destroyed before yourmemcpy
due to Mojo's ASAP destruction. Can be fixed by retainingtmp
with_ = tmp
.There are other ways to write this code. The following is slightly better:
I think the best option is to use
swap
from the stdlib: