Instead of object creation, C has a low-level notion of dynamic memory allocation.
allocation
The program calls a function requesting a chunk of memory of a certain size. The system finds such a chunk, and returns a pointer to it. The memory can be cast to be whatever type is needed.
de-allocation
There is no garbage collection in C. When the allocated memory is no longer needed, it is the programmer’s responsibility to free it. This requires discipline.
heap vs. stack
The pool of memory where such chunks live is called the heap. It is managed by the operating system.
By contrast, variables declared in routine bodies is said to live on the stack. The stack grows as the program enters into routines, and shrinks as it exits them.
example: linked list
dangers
-
allocation fails
(allocation call returns
null
) need to recover gracefully -
fail to free allocated memory
called a memory leak
other considerations
- memory allocation by the system takes some time
- more memory is usually allocated than actually requested
These are very system-dependent, and usually unproblematic. However, when doing millions of allocations, consider a custom memory allocation.