Friday, March 6, 2009

Dynamic Memory Allocation

DMA - Dynamic memory allocation

This means memory is allocated for a variable at runtime as and when a request is made .When we use char pointers to store data , we usually have just declared a pointer like char *ptr . Here ptr is allocated a memory of 2 bytes only.If we now want to store data we first have to allocate enough memory for that data . We have to call malloc( ) . In that call we have to specify how many bytes of space we need . malloc() returns a pointer to such a location

malloc( ) : The function malloc( ) Allocates memory

Declaration : void *malloc(size_t size);

malloc( ) allocates a block of size bytes from the memory heap. It allows a program to allocate memory explicitly as it's needed, and in the exact amounts needed. On success, malloc returns a pointer to the newly allocated block of memory. On error (if not enough space exists for the new block), malloc returns null. contents of the block are left unchanged.If the argument size == 0, malloc returns null.We have to explicitly typecast the kind of pointer we want as malloc() returns a void * by default . A void pointer is called as a generic pointer. It can be typecast into different types of pointers

free( ) : The function free( ) is called with pointers to free the memory allocated with malloc( ) e.g free(ptr);

No comments: