Dyna 2
Dyna 2
One completed block is allocated and malloc returns a pointer/base address of the block which is
allocated
Therefore, to allocate memory dynamically we need pointers without pointers we cannot allocate
memory.
(Void*) Malloc(size)
Size can only take 0 or positive values it cannot take negative values memory cannot be in negative
values
Since the malloc function doesn’t know the kind of value that gets stored in the 8bytes we use void
in this case based on the requirement we can change the return type of the malloc function
If we want to store integer function we can use int* if we want to store float then we can use float*
We usually don’t mention 20 or 8 any numerical values in the brackets we use certain method for
that also
Ptr(pointer)
Ptr=int* malloc(n*sizeof(int))
Int *ptr means this ptr is gonna store the address of a variable whose data type is an integer
If we don’t initialise the size of the memory then the malloc function takes some garbage value
If it is sufficient then it will retun the base address of the the block aloocated for the memory
Calloc in c
Calloc full form is contagious allocation
Built in function in stdlib.h library
Used to dynamically allocate multiple blocks of memory and each block is of the same size.
Malloc allocates single block of memory calloc allocates multiple blocks of memory
Realloc:
Reallocation,
Can be used only when malloc or calloc function is used to allocate memory in the programme.
Accepts 2 arguments, previously allocated pointer and the new size we want to resize it with.
Syntax:
(Void*)Realloc(void*ptr,size_t size);
The most important feature of realloc is that it resizes the memory block without losing the previous
content.
Ex; From heap section suppose we store
Int *ptr; five integers and let the first byte
address be 1000, then ptr returns
Ptr=(Int*) malloc(5*sizeof(int)); 1000, suppose now we want to add
2 more blocks of memory then we
Ptr1=(int*)realloc(ptr,7*sizeof(int));
do the following. The previous
content will be as it is and the first
byte address also remains the same
if the same block is expanded.
Syntax:
Void Free(pointer)
Ex:
Int *ptr;
Ptr=(int*)malloc(2*sizeof(int));
Free(ptr);