iOS Development

Course No. 10-152-139

Chapter 12 — The Heap

malloc()

  • Variables created in a function are on the stack and go away when the function ends.
  • When we need to have a lot of data in RAM we use the malloc() function to grab a chunk of memory that is not on the stack. It’s in what we all the heap. This is memory that is available to your program but is not automatically allocated for you. We have to do this memory allocation our selves. When we are done with it we have to free() it up ourselves, too.
  • We can put structs on the heap, too.
  • Let’s look at this line more closely.
  • First declare a pointer to our struct:
  • Next, get the size of what a variable of our struct will be.
  • Now grab some memory that can hold our struct.
  • This is called a cast. We need this so that the memory we get back from malloc can be used with our type.
  • This concept is really important when we start learning about objects.