Advanced Swift: Unsafe Memory Access, Episode 3: Unsafe Fundamentals | Kodeco, the new raywenderlich.com

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

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.

  1. Why do we need to deinitilize typed pointers but not raw pointers?
  2. Is it just a good practice to deallocate the initial pointer rather than the typed pointer or is there more to it? I’ve tried deallocating the typed pointer instead of the raw pointer and it seem to have worked correctly. I did get a crash when I tried deallocating the raw pointer after the typed pointer was already deallocated.

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.

2 Likes

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.