Compare heap and stack memory. Explain how each is allocated and freed, typical lifetimes of data stored there, access patterns and performance characteristics (allocation cost, locality, cache behavior), thread visibility (thread-local stacks vs shared heap), and common pitfalls such as stack overflow, heap fragmentation, and escaping references. Provide examples of when you would prefer one over the other and discuss how recursion depth and large objects affect the choice.