Skip to content

memcpy not working when creating new Tensor inside swap #1935

Closed Locked Answered by soraros
AlienKevin asked this question in Q&A
Discussion options

You must be logged in to vote

.data() is unsafe API, and tmp is destroyed before your memcpy due to Mojo's ASAP destruction. Can be fixed by retaining tmp with _ = tmp.

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 swap from the stdlib:

from algori…

Replies: 1 comment 3 replies

Comment options

You must be logged in to vote
3 replies
@AlienKevin
Comment options

@AlienKevin
Comment options

@soraros
Comment options

Answer selected by AlienKevin
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants