You are on page 1of 14

Dynamic Memory Management

Memory Layout 2

Memory Layout of a C Executable


Command line arguments and
High Address Args and env vars
environment variables
Stack
|
V

Unused memory
^
|
Heap

Uninitialized Data Segment (bss) Initialized to zero by exec.

Initialized Data Segment Read from the program file by exec.

Low Address Text Segment Read from the program file by exec.

Slide Title | CONFIDENTIAL 2006 December 8, 2021


“The contents here are for Aricent internal training purposes only and do not carry any commercial value”
Dynamic Memory Management 3

 Dynamic allocation is a pretty unique feature to C

 It enables us to create data types and structures of any size


and length to suit our programs needed within the program

 What is the need or advantage of allocating memory at run


time?

Slide Title | CONFIDENTIAL 2006 December 8, 2021


“The contents here are for Aricent internal training purposes only and do not carry any commercial value”
Dynamic memory allocation - malloc 4

 void *malloc(size_t nsize)

• Returns a pointer to space for an object of size nsize or NULL if the request cannot
be satisfied.

• Space allocated is uninitialised

 An example

int * iptr;
iptr=(int*) malloc(sizeof(int));
*iptr=40;

 There is a need to type cast the return value.

Slide Title | CONFIDENTIAL 2006


December 8, 2021
“The contents here are for Aricent internal training purposes only and do not carry any commercial value”
Dynamic Memory Allocation - free 5

 void free(void *ptr)

• Deallocates the space pointed to by p

• Does nothing if p is Null

• p must be a pointer to space previously allocated by calloc , malloc, or realloc.

• Example

free (iptr)
• After freeing the allocated memory do not use the pointer.

Slide Title | CONFIDENTIAL 2006 December 8, 2021


“The contents here are for Aricent internal training purposes only and do not carry any commercial value”
Dynamic Memory Allocation 6

int main()
{
int n, i, *p, sum=0;
float avg;
printf(“How many numbers?”);
scanf(“%d”, &n);
p = (int *) malloc(n*sizeof(int));
if(p)
{
for(i=0;i<n;i++)
{
scanf(“%d”,(p+i));
sum=sum+*(p+i);
}
avg =(float)sum / n;
printf(“The average = %f”, avg);
}
else printf(“Unsuccessfull Allocation”);
}
Slide Title | CONFIDENTIAL 2006 December 8, 2021
“The contents here are for Aricent internal training purposes only and do not carry any commercial value”
Dynamic Memory Allocation - calloc 7

 void *calloc (size_t n_elements ,size_t element_size)


• Returns a pointer to space for an array of n_elements objects , each of
size element_size bytes

• Returns NULL if the request cannot be satisfied

• Space is initialised to default value

• Example

• int *a = (double *)calloc(10,sizeof(double));

Slide Title | CONFIDENTIAL 2006 December 8, 2021


“The contents here are for Aricent internal training purposes only and do not carry any commercial value”
Dynamic Memory Allocation - realloc 8

 void *realloc(void *ptr, size_t size)


• Changes the size of the object pointed to by ptr to size

• Contents will be unchanged up to the minimum of old and new sizes.

• If the new size is larger , the new space is un initialised.

• Returns a pointer to the new space

• NULL if the request cannot be satisfied (*ptr is unchanged)

 While using realloc , if the memory is readjusted then there can


be other pointers which refer to some position in the old
previously allocated block.

 So when using realloc it may be necessary to readjust if realloc


returns a different location.
Slide Title | CONFIDENTIAL 2006 December 8, 2021
“The contents here are for Aricent internal training purposes only and do not carry any commercial value”
Dynamic Memory Allocation - realloc 9


Example
Suppose INITIAL_ARRAY_SIZE IS 10. Need it to increase by 5 units.
int *tmp;
/*ip is the pointer which is pointing to the old block of memory*/
/*tmp required since realloc may fail and the pointer for the old allocation may be assigned to NULL */
/*So the pointer is updated on realloc 's success*/

if ((tmp = realloc(ip, sizeof(int) * (INITIAL_ARRAY_SIZE + 5))) == NULL)


printf("ERROR: realloc failed");
else
ip = tmp;

Slide Title | CONFIDENTIAL 2006 December 8, 2021


“The contents here are for Aricent internal training purposes only and do not carry any commercial value”
Dynamic Memory Allocation - Memory Leak 10

 It is possible to allocate space for objects (variables) dynamically


during program execution.

 After finishing use of a dynamically allocated object


– It is necessary to explicitly release the memory consumed by the object, particularly before
pointers to the object go out of scope

– Memory allocated by malloc always persists until it is being freed explicitly.

 Failure to do so results in a memory leak.


 A memory leak can diminish the performance of the computer by
reducing the amount of available memory.

Slide Title | CONFIDENTIAL 2006 December 8, 2021


“The contents here are for Aricent internal training purposes only and do not carry any commercial value”
Memory Leak - Example 11

int f(void)
{
char * s ;
s = (char *)malloc(50 * sizeof(char)); /* get memory */
if (s==NULL)
{ return 1; /* no memory available */ }
else
{
/* memory available */
/*do something but free it before the return */
return 0; /* memory leak */
}
}
int main(void)
{ f();
return 0;
}

Slide Title | CONFIDENTIAL 2006 December 8, 2021


“The contents here are for Aricent internal training purposes only and do not carry any commercial value”
2D Array and Dynamic Memory Allocation 12

 Allocating memory dynamically for a 2D array

– double **a = (double **)calloc(m, sizeof(double*));


– for (index = 0; index < m; index += 1)
• a[index] = (double *) calloc(n, sizeof(double));

 Instead of doing m calls to calloc, we can make one big:


• double* a = (double *) calloc(m * n, sizeof(double));

 What is the difference between the two approaches?

Slide Title | CONFIDENTIAL 2006 December 8, 2021


“The contents here are for Aricent internal training purposes only and do not carry any commercial value”
Dynamic Memory - Assignment 13

 Implement the following


• Accept different strings from user till enters “quit”

• Concatenate these strings each time to a dynamically memory allocated character


array

• Determine how much memory to be reallocated from the length of user input

• Avoid memory leak

Slide Title | CONFIDENTIAL 2006 December 8, 2021


“The contents here are for Aricent internal training purposes only and do not carry any commercial value”
Dynamic Memory - Assignment 14

 Implement a program to fill a table of integers using array of


pointers

– Accept number of rows from the user

– Accept the length of each row from the user

– Accept elements row by row, each time, and fill the table

– Display the table, row –wise

– Do it as a multi-file program

– Create a make file

Slide Title | CONFIDENTIAL 2006 December 8, 2021


“The contents here are for Aricent internal training purposes only and do not carry any commercial value”

You might also like