Junior — Middle
How is data stored in the dynamic memory area (heap)?
sobes.tech AI
Answer from AI
Dynamic memory (heap) is a memory area from which a program allocates and frees memory during runtime as needed.
Data storage in the heap occurs as follows:
- When a memory request is made (for example, using malloc in C or new in C++), a block of the required size is allocated.
- Memory is not organized as a stack, so objects can be located in arbitrary places.
- Memory management is handled by the programmer (in languages without a garbage collector) or by the garbage collector (in languages with GC).
- In iOS, when using Objective-C or Swift, objects are usually allocated in the heap, and memory management is done through ARC (Automatic Reference Counting).
Example in Swift:
class Person {
var name: String
init(name: String) {
self.name = name
}
}
let person = Person(name: "Ivan") // object is created in the heap