Memory Lifetime

Initialized and uninitialized data segment variables are around during the entire run time of the program. They will not go away. Memory on the heap is explicitly requested and explicitly released. Memory here can be deallocated, but it’s under program control. Memory on the stack goes away, meaning that it can be reused by someone else as soon as it goes out of scope, even before a function exits, like within brace-delimited blocks within a function. The stack memory behavior can cause errors if you assume that memory will be valid longer than it actually is. A classic error is returning an address on the stack:

c​h​a​r​ ​*​f​r​o​b​u​l​a​t​e​ ​(​v​o​i​d​)​ ​{​ ​ ​ ​ ​c​h​a​r​ ​b​u​f​f​e​r​[​5​0​0​0​]​;​ ​ ​ ​ ​/​/​ ​w​o​r​k​ ...

Get Advanced Mac OS X Programming: The Big Nerd Ranch Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.