Sunday, June 18, 2006

Static vs. Dynamic Memory Allocation & Stack vs. Heap

http://www.cs.jcu.edu.au/Subjects/cp2003/1997/foils/heapAndStack/heapAndStack.html

> example
>
>int x; /* static storage */
>
>void main() {
> int y; /* dynamic stack storage */
> char *str; /* dynamic stack storage */
>
> str = malloc(100); /* allocates 100 bytes of dynamic heap storage */
>
> y = foo(23);
> free(str); /* deallocates 100 bytes of dynamic heap storage */
>} /* y and str deallocated as stack frame is popped */
>
>int foo(int z) { /* z is dynamic stack storage */
> char ch[100]; /* ch is dynamic stack storage */
>
> if (z == 23) foo(7);
>
> return 3; /* z and ch are deallocated as stack frame is popped,
> 3 put on top of stack */
>}
>

No comments:

Post a Comment