CS415: Systems programming
Memory management (malloc, calloc, free, realloc, memset, memcpy, strcpy)
1
Most of the slides in this lecture are either from or adapted from the slides provided by Dr. Ahmad Barghash
CS415: Systems programming Memory management (malloc, calloc, free, - - PowerPoint PPT Presentation
CS415: Systems programming Memory management (malloc, calloc, free, realloc, memset, memcpy, strcpy) 1 Most of the slides in this lecture are either from or adapted from the slides provided by Dr. Ahmad Barghash Memory allocation There are
Memory management (malloc, calloc, free, realloc, memset, memcpy, strcpy)
1
Most of the slides in this lecture are either from or adapted from the slides provided by Dr. Ahmad Barghash
❑Static – Done by the compiler automatically.
❖Global variables or objects -- memory is allocated at the start of the program, and freed when program exits; alive throughout program execution
Can be access anywhere in the program.
❖Local variables (inside a routine) – memory is allocated when a routine (e.g., a block, a function) starts and freed when the routine returns.
A local variable cannot be accessed from another routine.
❖Allocation and free are done automatically. ❖No need to explicitly manage memory is nice (easy to work with), but has limitations!
❖Using static allocation, the array size must be fixed. ❖Once allocated, memory cannot be resized
2
❑Wouldn’t it be nice to be able to have an array whose size can be adjusted depending on needs.
❖Dynamic memory allocation deals with this situation.
❑Dynamic – Done explicitly by programmer.
❖Programmer explicitly requests the system to allocate memory and return starting address of memory allocated. ❖ This address can be used by the programmer to access the allocated memory. ❖When done using memory, it must be explicitly freed.
3
4
insufficient, allocation fails and returns a NULL pointer.
5
6
7
4 bytes ptr = 20 bytes of memory A large 20 bytes memory block is Dynamically allocated to ptr
8
9
ptr = (cast-type*) calloc(n, element-size);
initialized each item with a default value ‘0’. If space is insufficient, allocation fails and returns a NULL pointer.
10
4 bytes ptr = 20 bytes of memory 5 blocks of 4 bytes each is Dynamically allocated to ptr 4 bytes
11
12
Note: It would be better to use malloc over calloc, unless we want the zero-initialization because malloc is faster than calloc. So if we just want to copy some stuff or do something that doesn’t require filling of the blocks with zeros, then malloc would be a better choice. We can achieve same functionality as calloc() by using malloc() followed by memset().
ptr = malloc(size); memset(ptr, 0, size);
13
change the memory allocation of a previously allocated memory. In other words, if the memory previously allocated with the help of malloc or calloc is insufficient, realloc can be used to dynamically re-allocate memory.
ptr = realloc(ptr, newSize);
This function returns a pointer to the newly allocated memory, or NULL if the request fails.
14
4 bytes ptr = 20 bytes of memory A large 20 bytes memory block is Dynamically allocated to ptr
ptr = 40 bytes of memory The size of ptr is changed from 20 bytes to 40 bytes dynamically
15
16
17
18
int *a; A=(int *) calloc(5, sizeof(int)); A[0]=8; *(A+2)=3; A[3]=9;
1st element of the allocated memory 3rd element of the allocated memory 4th element of the allocated memory
19
20
The memory allocated using functions malloc() and calloc() is not de-allocated on their own. Hence, the free() method is used, whenever the dynamic memory allocation takes place. It helps to reduce wastage of memory by freeing it.
void free(void *ptr)
The Compiler would say….
21
allocated memory
dynamically allocated memory
till the end of the program’s lifetime
22
char* strcpy(char* dest, const char* src);
(including the null character) to the character array destination.
23
#include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char name[100]; strcpy(name, “Abdullah Alfarrarjeh"); char *description; /* allocate memory dynamically */ description = malloc( 100 * sizeof(char) ); if( description == NULL ) { fprintf(stderr, "Error - unable to allocate required memory\n"); } else { strcpy( description, “Welcome CS415 Students"); } printf("Name = %s\n", name ); printf("Description: %s\n", description ); free(description); return 0; }
24
#include <stdio.h> #include <stdlib.h> int main() { char *str; /* Initial memory allocation */ str = (char *) malloc(15); strcpy(str, "tutorialspoint"); printf("String = %s, Address = %u\n", str, str); /* Reallocating memory */ str = (char *) realloc(str, 25); strcat(str, ".com"); printf("String = %s, Address = %u\n", str, str); free(str); return(0); } String = tutorialspoint, Address = 355090448 String = tutorialspoint.com, Address = 355090448
25
#include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char name[100]; char *description; strcpy(name, "Zara Ali"); /* allocate memory dynamically */ description = malloc( 30 * sizeof(char) ); if( description == NULL ) { fprintf(stderr, "Error - unable to allocate required memory\n"); } else { strcpy( description, “CS415 student."); } /* suppose you want to store bigger description */ description = realloc( description, 100 * sizeof(char) ); if( description == NULL ) { fprintf(stderr, "Error - unable to allocate required memory\n"); } else { strcat( description, “Students of CS415"); } printf("Name = %s\n", name ); printf("Description: %s\n", description ); /* release memory using free() function */ free(description); } Name = Zara Ali Description: CS415 student.Students of CS415
26
void *memcpy(void *str1, const void *str2, size_t n)
This function returns a pointer to destination, which is str1.
28
//this will copy string from source(src) to destination(dst). char *strcpy(char *dst, const char *src); // this will copy n number of memory bytes from memory pointing to in to the memory pointing to out. void* memcpy(void *restrict out, const void *restrict in, size_t n);
#include <stdio.h> #include <string.h> int main () { const char src[50] = "http://www.tutorialspoint.com"; char dest[50]; printf("Before memcpy dest = %s\n", dest); memcpy(dest, src, strlen(src)+1); printf("After memcpy dest = %s\n", dest); return(0); }
Before memcpy dest = After memcpy dest = http://www.tutorialspoint.com
#include <stdio.h> #include <stdlib.h> int main() { int *iVar; char *cVar; float *fVar; iVar=(int*)malloc(1*sizeof(int)); cVar=(char*)malloc(1*sizeof(char)); fVar=(float*)malloc(1*sizeof(float)); printf("Enter integer value: "); scanf("%d",iVar); printf("Enter character value: "); scanf(" %c",cVar); printf("Enter float value: "); scanf("%f",fVar); printf("Inputted value are: %d, %c, %.2f\n",*iVar,*cVar,*fVar); /*free allocated memory*/ free(iVar); free(cVar); free(fVar); return 0; }
Enter integer value: 100 Enter character value: x Enter float value: 123.45 Inputted value are: 100, x, 123.45
#include <stdio.h> #include <stdlib.h> int main() { int *arr; int limit,i; int sum=0; printf("Enter total number of elements: "); scanf("%d",&limit); /*allocate memory for limit elements dynamically*/ arr=(int*)malloc(limit*sizeof(int)); if(arr==NULL) { printf("Insufficient Memory, Exiting... \n"); return 0; } printf("Enter %d elements:\n",limit); for(i=0; i<limit; i++) { printf("Enter element %3d: ",i+1); scanf("%d",(arr+i)); /*calculate sum*/ sum=sum + *(arr+i); } printf("Array elements are:"); for(i=0; i<limit; i++) printf("%3d ",*(arr+i)); printf("\nSum of all elements: %d\n",sum); return 0; }
Enter total number of elements: 5 Enter 5 elements: Enter element 1: 11 Enter element 2: 22 Enter element 3: 33 Enter element 4: 44 Enter element 5: 55 Array elements are: 11 22 33 44 55 Sum of all elements: 165
#include <stdio.h> #include <stdlib.h> /*structure declaration*/ struct student { char name[30]; int roll; float perc; }; int main() { struct student *pstd; /*Allocate memory dynamically*/ pstd=(struct student*)malloc(1*sizeof(struct student)); if(pstd==NULL) { printf("Insufficient Memory, Exiting... \n"); return 0; } /*read and print details*/ printf("Enter name: "); gets(pstd->name); printf("Enter roll number: "); scanf("%d",&pstd->roll); printf("Enter percentage: "); scanf("%f",&pstd->perc); printf("\nEntered details are:\n"); printf("Name: %s, Roll Number: %d, Percentage: %.2f\n",pstd->name,pstd->roll,pstd->perc); return 0; }
Enter name: Mike Enter roll number: 1 Enter percentage: 87.50 Entered details are: Name: Mike, Roll Number: 1, Percentage: 87.50
#include <stdio.h> #include <stdlib.h> struct student { char name[30]; int roll; float perc; }; int main() { struct student *pstd; int n,i; printf("Enter total number of elements: "); scanf("%d",&n); pstd=(struct student*)malloc(n*sizeof(struct student)); if(pstd==NULL) { printf("Insufficient Memory, Exiting... \n"); return 0; } /*read and print details*/ for(i=0; i<n; i++) { printf("\nEnter detail of student [%3d]:\n",i+1); printf("Enter name: "); scanf(" "); /*clear input buffer*/ gets((pstd+i)->name); printf("Enter roll number: "); scanf("%d",&(pstd+i)->roll); printf("Enter percentage: "); scanf("%f",&(pstd+i)->perc); } printf("\nEntered details are:\n"); for(i=0; i<n; i++) { printf("%30s \t %5d \t %.2f\n",(pstd+i)->name,(pstd+i)->roll,(pstd+i)->perc); } return 0;}
Enter total number of elements: 3 Enter detail of student [1]: Enter name: Mike Enter roll number: 1 Enter percentage: 87.50 Enter detail of student [2]: Enter name: Jussy Enter roll number: 2 Enter percentage: 88 Enter detail of student [3]: Enter name: Macalla Enter roll number: 3 Enter percentage: 98.70 Entered details are: Mike 1 87.50 Jussy 2 88.00 Macalla 3 98.70
Function Description malloc allocates the specified number of bytes realloc increases or decreases the size of the specified block of memory, moving it if necessary calloc allocates the specified number of bytes and initializes them to zero free releases the specified block of memory back to the system
35