In this video we will explore the fundamentals of unsafe memory access, and learn about the types involved.
This is a companion discussion topic for the original entry at https://www.kodeco.com/1940773-advanced-swift-unsafe-memory-access/lessons/3
In this video we will explore the fundamentals of unsafe memory access, and learn about the types involved.
Hi Team,
Could you explain why it is important to deinitialise a typed pointer before we deallocate it? Ray mentioned that it is important but didn’t explain what happens if we don’t.
Thank you!
Sorry, probably a silly question, but what does deinitialising actually do? Does it replace the bits with zeros?
Another two-part follow up question. When we have converted a raw pointer to a typed pointer, Ray has mentioned that we need to deinitialise the typed pointer but deallocate the raw pointer.
In the more obvious case, it calls deinit if you are dealing with a class (or, now, also an actor). This is part of the contract which is why you need to do it exactly once. Although I think this gets optimized a way for something like Int
types you are still supposed to do it.
Raw pointers do not have a type bound to them so there it doesn’t know what to do (what init to call).
Memory needs to be deallocated exactly once. That is the danger of unsafe stuff. If you do something wrong you are lucky if you get a crash. In the worst case you get UB (the dreaded undefined behavior).
Hope that helps.
Yes, very much so, thank you!
Hi @allanspreys,
We hope that the response provided by @rayfix was helpful in addressing your concerns.
If you have any further questions or need additional assistance, please don’t hesitate to ask.