Monday 20 July 2015

Memory Allocation in C !

The hacker must understand the way C organizes memory for its program. As we have already discussed, a C compiled program’s memory is divided into five segments: text, data, bss, heap, and stack.

                                           
                       


The text segment is also sometimes called the code segment. This is where the assembled machine language instructions of the program are located.The data and bss segments are used to store global and static program variables. The data segment is filled with the initialized global and static variables, while the bss segment is filled with their uninitialized counterparts.The heap segment is a segment of memory a programmer can directly control. Blocks of memory in this segment can be allocated and used for whatever the programmer might need.The stack is used for holding the return addresses at function calls, arguments passed to the functions, and local variables for functions.

Dynamic and static allocation of memory :
The golden rule of computers states that anything and everything(data or instruction) that needs to be processed must be loaded into internal memory before its processing takes places. Therefore, every data and instruction that is being executed must be allocated some area in the main memory.
The main memory is allocated in two ways:
Statically
Dynamically

Static memory allocation: In static memory allocation, memory is allocated while writing the C program. Actually, user requested memory will be allocated at compile time. Memory size can’t be modified while execution.
Example: array
Dynamic memory allocation:In dynamic memory allocation, memory is allocated while executing the program. That means at run time.Memory size can be modified while execution.
Example: Linked list

Dynamic memory allocation functions in C:
C language inherently does not has any technique to allocated memory dynamically, there are 4 library functions under "stdlib.h" for dynamic memory allocation:
Function        Syntax                                                                                   Description
malloc()       malloc (number *sizeof(int));          Allocates requested size of bytes
                                                                                                          and returns a pointer first byte
                                                                                                          byte of allocated space


calloc()     calloc (number, sizeof(int));     Allocates space for an array elements,
                                                                                                       initializes to zero and then returns a
                                                                                                       pointer to memory
realloc()    realloc(pointer_name,number *sizeof(int));Change the size of
                                                                                                                         previously allocated space

free()        free (pointer_name);                        dellocate the previously allocated space   


malloc():
malloc () function is used to allocate space in memory during the execution of the program.
Here is the prototype:
void* malloc(size_t size);
type “size_t” is used for defining sizes of strings and memory blocks.The size_t argument is the size of memory block you want to be allocated to your code by the operating system.
malloc() returns a pointer to a void. it doesn't care weather you are allocating this memory to store character, interger etc. , it simply returns void data types. We can correct this using a technique call a “typecasting”.
malloc () does not initialize the memory allocated during execution.  It carries garbage value.
The malloc() function returns a pointer to an area of memory with size of byte size. If the space is insufficient, allocation fails and returns NULL pointer.

num=(int*)malloc(100*sizeof(int));
This statement will allocate either 200 or 400 according to size of int 2 or 4 bytes respectively and the pointer points to the address of first byte of memory.

calloc() : 
calloc () function is also like malloc () function. The only difference between malloc() and calloc() is that, malloc() allocates single block of memory whereas calloc() allocates multiple blocks of memory each of same size  and sets all bytes to zero.
Here is the prototype:
void  *calloc(size_t n, size_t size);

num=(float*)calloc(25,sizeof(float));
This statement allocates contiguous space in memory for an array of 25 elements each of size of float, i.e, 4 bytes.

free():
Dynamically allocated memory with either calloc() or malloc() does not get return on its own. The programmer must use free() explicitly to release space.

free(num);
This statement cause the space in memory pointer by num to be deallocated.

realloc():
If the previously allocated memory is insufficient or more than sufficient. Then, you can change memory size previously allocated using realloc(). realloc() function modifies the allocated memory size by malloc () and calloc () functions to new size.
Here is the prototype:
void  *realloc(void *num, size_t newsize);
If enough space doesn’t exist in memory of current block to extend, new block is allocated for the full size of reallocation, then copies the existing data to new block and then frees the old block.

Stack vs Heap allocation:
Stack:
very fast access
don't have to explicitly de-allocate variables
space is managed efficiently by CPU, memory will not become fragmented
local variables only
limit on stack size (OS-dependent)
variables cannot be resized

Heap :
variables can be accessed globally
no limit on memory size
slower access
no guaranteed efficient use of space, memory may become fragmented over time as blocks of memory are allocated, then     freed
you must manage memory (you're in charge of allocating and freeing variables)
variables can be resized using realloc()

When to use the Heap?
When should you use the heap, and when should you use the stack? If you need to allocate a large block of memory (e.g. a large array, or a big struct), and you need to keep that variable around a long time (like a global), then you should allocate it on the heap. If you are dealing with relatively small variables that only need to persist as long as the function using them is alive, then you should use the stack, it's easier and faster. If you need variables like arrays and structs that can change size dynamically (e.g. arrays that can grow or shrink as needed) then you will likely need to allocate them on the heap, and use dynamic memory allocation functions like malloc(), calloc(), realloc() and free() to manage that memory "by hand". We will talk about dynamically allocated data structures after we talk about pointers.

Reference:
Memory : Stack vs Heap

If you like this post or have any question, please feel free to comment !

No comments:

Post a Comment

Blogger Widget