Upload
sakthi-ganesh
View
55
Download
3
Embed Size (px)
Citation preview
Dynamic Memory Management
“The contents here are for Aricent internal training purposes only and do not carry any commercial value”
2
April 7, 2023Slide Title | CONFIDENTIAL 2006
Memory Layout
Memory Layout of a C Executable
High Address Args and env varsCommand line arguments and
environment variables
Stack|V
Unused memory
^|
Heap
Uninitialized Data Segment (bss) Initialized to zero by exec.
Initialized Data SegmentRead from the program file by
exec.
Low Address Text SegmentRead from the program file by
exec.
“The contents here are for Aricent internal training purposes only and do not carry any commercial value”
3
April 7, 2023Slide Title | CONFIDENTIAL 2006
Dynamic Memory Management
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?
“The contents here are for Aricent internal training purposes only and do not carry any commercial value”
4
April 7, 2023Slide Title | CONFIDENTIAL 2006
Dynamic memory allocation - malloc
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.
“The contents here are for Aricent internal training purposes only and do not carry any commercial value”
5
April 7, 2023Slide Title | CONFIDENTIAL 2006
Dynamic Memory Allocation - free
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.
“The contents here are for Aricent internal training purposes only and do not carry any commercial value”
6
April 7, 2023Slide Title | CONFIDENTIAL 2006
Dynamic Memory Allocation
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”);
}
“The contents here are for Aricent internal training purposes only and do not carry any commercial value”
7
April 7, 2023Slide Title | CONFIDENTIAL 2006
Dynamic Memory Allocation - calloc
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));
“The contents here are for Aricent internal training purposes only and do not carry any commercial value”
8
April 7, 2023Slide Title | CONFIDENTIAL 2006
Dynamic Memory Allocation - realloc
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.
“The contents here are for Aricent internal training purposes only and do not carry any commercial value”
9
April 7, 2023Slide Title | CONFIDENTIAL 2006
Dynamic Memory Allocation - realloc
● ExampleSuppose 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;
“The contents here are for Aricent internal training purposes only and do not carry any commercial value”
10
April 7, 2023Slide Title | CONFIDENTIAL 2006
Dynamic Memory Allocation - Memory Leak
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.
“The contents here are for Aricent internal training purposes only and do not carry any commercial value”
11
April 7, 2023Slide Title | CONFIDENTIAL 2006
Memory Leak - Example
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; }
“The contents here are for Aricent internal training purposes only and do not carry any commercial value”
12
April 7, 2023Slide Title | CONFIDENTIAL 2006
2D Array and Dynamic Memory Allocation
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?
“The contents here are for Aricent internal training purposes only and do not carry any commercial value”
13
April 7, 2023Slide Title | CONFIDENTIAL 2006
Dynamic Memory - Assignment
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
“The contents here are for Aricent internal training purposes only and do not carry any commercial value”
14
April 7, 2023Slide Title | CONFIDENTIAL 2006
Dynamic Memory - Assignment
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