M
Modular•10mo ago
Francesco

Question from a low level memory management noob

I am trying to get familiar with some concepts for low level memory management. Coming from python this is all new for me although I do grasp the basics. I was playing around with tensors and buffers and seeing something that I find very strange so maybe understanding why this program behaves like this will hopefully help me understand something new 🙂 the first time I call print(abuf[2]) yields the correct value (2.0). The second time it's a random number. Why does this happen? `py from tensor import Tensor alias type = DType.float32 fn main(): var a = Tensor[type](100) for i in range(100): a[i] = i let abuf = a._to_buffer() print(abuf[2]) # 2.0 print(a[2]) # 2.0 print(a[2]) # 2.0 print(abuf[2]) # some random number... why?
5 Replies
sora
sora•10mo ago
Mojo has ASAP destruction, so a is destroyed after the second pirnt(a[2]). If you put _ = a at the very end, the problem goes away. I think it's "working as expected" for now, as the lifetime checker is not enabled fully. When it's enabled, the reference to a should prevent it from being destructed.
Francesco
FrancescoOP•10mo ago
@sora Thanks! That explains it. If I may, I'd have a follow up question. The problem only arises for indices < 4, but when indexing e.g. abuf[20] there is no problem and prints 20 as expected. Is there a specific reason why it's 4 and not something else?
ModularBot
ModularBot•10mo ago
Congrats @Francesco, you just advanced to level 1!
sora
sora•10mo ago
Maybe only the leading portion of the memory is reused for something else.
Nick!
Nick!•10mo ago
The general rule is that when you're reading from an invalid memory location, all bets are off regarding what value you are going to get. The compiler can reuse some or all of the memory for other purposes, and it's allowed to change its mind each time you compile or run the program.
Want results from more Discord servers?
Add your server