網頁

2011年1月8日 星期六

Dynamic Memory Allocation

In a software or firmware interview, you may be asked about dynamic memory allocation in different way.


What is dynamically memory allocation?
dynamic memory allocation (heap-based memory allocation) is the allocation of memory storage during the runtime of that program. Dynamically allocated memory exists until it is released either explicitly by the programmer. It is said that this object has a dynamic lifetime.


How to dynamically allocate memory in C?
malloc() provides dynamic memory allocation.

    void *  malloc (  size_t  size )

The type of returned pointer is *void since malloc doesn't know how you are going to use the allocated memory, so you need to cast it before using.


Memory Leak
When you don't need the allocated memory anymore, you must free it by calling free(). If you forgot to do it, the allocated memory will be always reserved and the system cannot use it, it is so called memory leak


free() releases the allocated memory.
    void  free (  void *p )
Example
        int *pA ;
        pA = ( int *) malloc (sizeof (int) * 10 ) ;  //
allocate 10 int ( 40 bytes )
        //use the allocated memory here
        free(pA);   //release the memory


Where is the dynamically allocated memory located?
The memory allocated by using malloc will be located in heap section.

沒有留言:

張貼留言