Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
124 views18 pages

Dynamic Memory for Developers

The document discusses dynamic memory allocation in C/C++. It explains that memory allocation can be handled at runtime using functions like malloc(), calloc(), and realloc() rather than just at compile time. Malloc allocates memory for a single block, calloc initializes allocated blocks to zero and allocates multiple blocks, and realloc changes the size of an existing memory block. Freeing allocated memory is important to prevent memory leaks, which occur when a program fails to free memory no longer needed.

Uploaded by

Gourav Gupta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
124 views18 pages

Dynamic Memory for Developers

The document discusses dynamic memory allocation in C/C++. It explains that memory allocation can be handled at runtime using functions like malloc(), calloc(), and realloc() rather than just at compile time. Malloc allocates memory for a single block, calloc initializes allocated blocks to zero and allocates multiple blocks, and realloc changes the size of an existing memory block. Freeing allocated memory is important to prevent memory leaks, which occur when a program fails to free memory no longer needed.

Uploaded by

Gourav Gupta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 18

Dynamic Memory Allocation

The memory usage for program data can increase or decrease as


your program runs.
Up until this point, the memory allocation for your program has
been handled automatically when compiling. However, sometimes
the computer doesn't know how much memory to set aside (for
example, when you have an unsized array).
The dynamic memory allocation functions give you the power to
dynamically allocate memory for your variables at RUN-
TIME (whilst the program is running). Before for the programs ,
memory was allocated when the program was compiled
(i.e.COMPILE-TIME).


malloc () and free()
void * malloc(size_t size);
void free(void * ptr);
malloc requires one argument - the number of
bytes you want to allocate dynamically.
If the memory allocation was
successful, malloc will return a void pointer - you
can assign this to a pointer variable, which will
store the address of the allocated memory.
If memory allocation failed (for example, if
you're out of memory), malloc will return a NULL
pointer.
Passing the pointer into free will release the
allocated memory - it is good practice to free
memory when you've finished with it.
Malloc Example
char *s = (char *) malloc (sizeof(*s))
sizeof operator
Takes a type or
expression, evaluates to the
number of bytes to store it
type cast
malloc returns
void *, cast tells compiler we are
using it as a
char *
This example will ask you how many integers you'd like to store in an array.
It'll then allocate the memory dynamically using malloc and store a certain
number of integers, print them out, then releases the used memory
usingfree.
#include <stdio.h>
#include <stdlib.h> /* required for the malloc and free
functions */
int main()
{
int number;
int *ptr; int i;
printf("How many ints would you like store? ");
scanf("%d", &number);
ptr = malloc(number*sizeof(int)); /* allocate memory */
if(ptr!=NULL)
{
for(i=0 ; i<number ; i++)
{
*(ptr+i) = i;
}
Continue.
for(i=number ; i>0 ; i--)
{
printf("%d\n", *(ptr+(i-1))); /* print out in
reverse order */
}
free(ptr); /* free allocated memory */
return 0;
}
else
{
printf("\nMemory allocation failed - not enough memory.\n");
return 1;
}
}

Output
Output if I entered 3:
How many ints would you like store? 3
2
1
0
Calloc()
void * calloc(size_t n, size_t el_size);

calloc is similar to malloc, but the main difference
is that the values stored in the allocated memory
space is zero by default. With malloc, the
allocated memory could have any value.
calloc requires two arguments. The first is the
number of variables you'd like to allocate
memory for. The second is the size of each
variable.
Like malloc, calloc will return a void pointer if the
memory allocation was successful, else it'll
return a NULL pointer.
This example shows you how to call calloc and also how
to reference the allocated memory using an array index.
The initial value of the allocated memory is printed out
in the for loop.
#include <stdio.h>
#include <stdlib.h> /* required for the malloc, calloc and
free functions */
int main()
{
float *c1, *c2, *m1, *m2;
int i;
c1 = calloc(3, sizeof(float)); /* might need to cast */
c2 = calloc(3, sizeof(float));
m1 = malloc(3 * sizeof(float));
m2 = malloc(3 * sizeof(float));

if(c1!=NULL && c2!=NULL && m1!=NULL && m2!=NULL)
{
for(i=0 ; i<3 ; i++)
{
printf(c1[%d] holds %05.5f, ", i, c1[i]);
printf(m1[%d] holds %05.5f\n", i, m1[i]);
printf(c2[%d] holds %05.5f, ", i, *(c2+i));
printf(m2[%d] holds %05.5f\n", i, *(m2+i));
}
free(c1);
free(c2);
free(m1);
free(m2);
return 0;
}
else
{
printf("Not enough memory\n");
return 1;
}
}
Output
c1[0] holds 0.00000, m1[0] holds -431602080.00000

c2[0] holds 0.00000, m2[0] holds -431602080.00000

c1[1] holds 0.00000, m1[1] holds -431602080.00000

c2[1] holds 0.00000, m2[1] holds -431602080.00000

c1[2] holds 0.00000, m1[2] holds -431602080.00000

c2[2] holds 0.00000, m2[2] holds -431602080.00000

On all machines, the c1 and c2 arrays should hold zeros. Contents of
the m1 and m2 arrays will vary.
malloc takes only the size of
the memory block to be
allocated as input
parameter.
1. calloc takes two
parameters: the number of
memory blocks and the size
of each block of memory
. malloc allocates memory
as a single contiguous
block.
. calloc allocates memory
which may/may not be
contiguous.
if a single contiguous block
cannot be allocated then
malloc would fail
. all the memory blocks are
initialized to 0.
. it follows from point 2 that
calloc will not fail if memory
can beallocated in non-
contiguous blocks when a
single contiguous
blockcannot be allocated
malloc () for allocating the
single block of memory
calloc () for allocating
multiple blocks of memory
the values assigned are
garbage in case of malloc()
proper values (zeros) are
assigned in case of calloc().
Realloc()
void * realloc(void * ptr, size_t size);
Now suppose you've allocated a certain number of bytes
for an array but later find that you want to add values to
it. You could copy everything into a larger array, which is
inefficient, or you can allocate more bytes using realloc,
without losing your data.
realloc takes two arguments. The first is the pointer
referencing the memory. The second is the total number
of bytes you want to reallocate.
Passing zero as the second argument is the equivalent of
calling free.
Once again, realloc returns a void pointer if successful, else
a NULL pointer is returned.
This example uses calloc to allocate enough memory for an int array
of five elements. Then realloc is called to extend the array to hold
seven elements.
#include<stdio.h>
#include <stdlib.h>
int main()
{
int *ptr;
int i;
ptr = calloc(5, sizeof(int));
if(ptr!=NULL)
{
*ptr = 1;
*(ptr+1) = 2;
ptr[2] = 4;
ptr[3] = 8;
ptr[4] = 16; /* ptr[5] = 32; wouldn't assign anything */
ptr = realloc(ptr, 7*sizeof(int));


if(ptr!=NULL)
{
printf("Now allocating more memory... \n"); ptr[5] = 32; /* now it's legal! */
ptr[6] = 64;
for(i=0 ; i<7 ; i++)
{
printf("ptr[%d] holds %d\n", i, ptr[i]);
}
realloc(ptr,0); /* same as free(ptr); - just fancier! */ return 0;
}
else
{
printf("Not enough memory - realloc failed.\n");
return 1;
}
}
else
{
printf("Not enough memory - calloc failed.\n");
return 1;
}
}
OUTPUT

Now allocating more memory...
ptr[0] holds 1
ptr[1] holds 2
ptr[2] holds 4
ptr[3] holds 8
ptr[4] holds 16
ptr[5] holds 32
ptr[6] holds 64
Notice the two different methods I used when initializing
the array: ptr[2] = 4; is the equivalent to *(ptr+2) =
4; (just easier to read!).


coreleft() :- returns the amount of
free memory in the heap.


unsigned coreleft(void);
Memory Leak
A condition caused by a program that
does not free up the extra memory it
allocates. In programming languages,
such as C/C++, the programmer can
dynamically allocate additional memory to
hold data and variables that are required
for the moment, but not used throughout
the program. When those memory areas
are no longer needed, the programmer
must remember to deallocate them.
Memory Leak(Contd..)
When memory is allocated, but not
deallocated, a memory leak occurs (the
memory has leaked out of the computer).
If too many memory leaks occur, they can
usurp all of memory and bring everything
to a halt or slow the processing
considerably.

You might also like