Wednesday, July 13, 2011

Dynamic memory allocation in C

Overview of memory management


Stack-allocated memory
  • When a function is called, memory is allocated for all of its parameters and local variables.
  • Each active function call has memory on the stack (with the current function call on top)
  • When a function call terminates,the memory is deallocated (“freed up”)
Ex: main() calls f(),
    f() calls g()
    g() recursively calls g()



Heap-allocated memory
  • This is used for persistent data, that must survive beyond the lifetime of a function call
  1. global variables
  2. dynamically allocated memory – C statements can create new heap data (similar to new in Java/C++)
  • Heap memory is allocated in a more complex way than stack memory
  • Like stack-allocated memory, the underlying system determines where to get more memory – the programmer doesn't have to search for free memory space
As we begin doing dynamic memory allocation, we'll begin to see (if we haven't seen it already) what pointers can really be good for. However, when we begin doing dynamic memory allocation, pointers are the only way to go, because what malloc returns is a pointer to the memory it gives us. (Due to the equivalence between pointers and arrays, though, we will still be able to think of dynamically allocated regions of storage as if they were arrays, and even to use array-like subscripting notation on them.)
You have to be careful with dynamic memory allocation. malloc operates at a pretty ``low level''; you will often find yourself having to do a certain amount of work to manage the memory it gives you. If you don't keep accurate track of the memory which malloc has given you, and the pointers of yours which point to it, it's all too easy to accidentally use a pointer which points ``nowhere'', with generally unpleasant results. (The basic problem is that if you assign a value to the location pointed to by a pointer

*p = 0;

and if the pointer p points ``nowhere'', well actually it can be construed to point somewhere, just not where you wanted it to, and that ``somewhere'' is where the 0 gets written. If the ``somewhere'' is memory which is in use by some other part of your program, or even worse, if the operating system has not protected itself from you and ``somewhere'' is in fact in use by the operating system, things could get ugly.)



No comments:

Post a Comment