CS415: Systems programming Memory management (malloc, calloc, free, - - PowerPoint PPT Presentation

cs415 systems programming
SMART_READER_LITE
LIVE PREVIEW

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


slide-1
SLIDE 1

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

slide-2
SLIDE 2

Memory allocation

There are essentially two types of memory allocation

❑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

slide-3
SLIDE 3

Memory allocation

  • There are essentially two types of memory allocation

❑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

slide-4
SLIDE 4

Dynamic Memory Allocation

  • C Dynamic Memory Allocation refers to performing manual memory

management for dynamic memory allocation in the C programming language via a group of functions in the C standard library, namely malloc, realloc, calloc and free. These functions are defined in the <stdlib.h> header file.

4

slide-5
SLIDE 5

malloc() Function

  • Function Syntax:

ptr = (cast-type*) malloc(byte-size)

  • Description:
  • reserves in memory the number of bytes specified in size
  • returns the start address of the new block of reserved memory. If space is

insufficient, allocation fails and returns a NULL pointer.

  • do not lose this!
  • Important points:
  • once allocated, memory is reserved until:
  • it is freed explicitly, using
  • free() function
  • program termination
  • if you lose a pointer to dynamically allocated memory, it stays

reserved anyway

5

slide-6
SLIDE 6

Example

double *a; a = (double *) malloc( sizeof(double) ); *a = 3.14; printf("%lf\n", *a); free(a);

6

slide-7
SLIDE 7

What do we call this?

double *a; a = (double *) malloc(sizeof(double)); a = (double *) malloc(sizeof(double));

Memory leak We need to free the memory

7

slide-8
SLIDE 8

“malloc” or “memory allocation”

int *ptr = (int *) malloc (5 * sizeof(int));

4 bytes ptr = 20 bytes of memory A large 20 bytes memory block is Dynamically allocated to ptr

8

slide-9
SLIDE 9

9

slide-10
SLIDE 10

calloc() Function

  • Function Syntax:

ptr = (cast-type*) calloc(n, element-size);

  • Description
  • Reserves in memory n items, each the number of bytes specified in size. It

initialized each item with a default value ‘0’. If space is insufficient, allocation fails and returns a NULL pointer.

  • Returns the start of the new block of reserved memory
  • Example:

double *a; a=(double *) calloc (70, sizeof(double));

10

slide-11
SLIDE 11

“calloc” or “contiguous allocation”

int *ptr = (int *) calloc (5, sizeof(int));

4 bytes ptr = 20 bytes of memory 5 blocks of 4 bytes each is Dynamically allocated to ptr 4 bytes

11

slide-12
SLIDE 12

malloc() vs. . calloc()

  • malloc() takes a single argument (the amount of memory to

allocate in bytes), while calloc() needs two arguments (the number of variables to allocate in memory, and the size in bytes of a single variable).

  • malloc() does not initialize the memory allocated, while

calloc() guarantees that all bytes of the allocated memory block have been initialized to 0.

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);

slide-13
SLIDE 13

13

slide-14
SLIDE 14

realloc() Function

  • realloc() or the “re-allocation” method in C is used to dynamically

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.

  • Function Syntax:

ptr = realloc(ptr, newSize);

  • ptr: Pointer to memory block to be reallocated
  • newSize: the new size of the memory block in bytes
  • Return Value

This function returns a pointer to the newly allocated memory, or NULL if the request fails.

14

slide-15
SLIDE 15

“realloc” or “re-allocation”

int *ptr = (int *) malloc (5 * sizeof(int));

4 bytes ptr = 20 bytes of memory A large 20 bytes memory block is Dynamically allocated to ptr

ptr = realloc (ptr, 10 * sizeof(int));

ptr = 40 bytes of memory The size of ptr is changed from 20 bytes to 40 bytes dynamically

15

slide-16
SLIDE 16

16

slide-17
SLIDE 17

17

slide-18
SLIDE 18

Can realloc() be used for shrinking an allocated memory?

  • Yes. Following is an example.

//allocating 100 elements int *myPointer = malloc(100*sizeof(int)); //shrinking memory from 100 to 50 elements myPointer = realloc(myPointer,50*sizeof(int));

When shrinking an allocated memory using realloc, does the "extra" memory get freed automatically?

  • Yes. There is no memory leak as the extra memory will be freed

automatically.

18

slide-19
SLIDE 19

Accessing Dynamically Allocated Memory

  • Dynamically allocated memory can be accessed:
  • Through pointers
  • Using array notation
  • Example:

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

slide-20
SLIDE 20

20

slide-21
SLIDE 21

Deallocating Dynamically Allocated Memory

  • The free() method in C is used to dynamically de-allocate the memory.

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.

  • Function prototype

void free(void *ptr)

  • Description:
  • Releases the memory pointed to by ptr

The Compiler would say….

21

slide-22
SLIDE 22

Memory Leaks

  • What is a memory leak?
  • When you lose pointer to dynamically

allocated memory

  • When you forget to deallocate

dynamically allocated memory

  • What is so bad about this?
  • You lose access to data in memory
  • Amount of memory available is not infinit
  • You will lose certain amount of memory

till the end of the program’s lifetime

22

slide-23
SLIDE 23

strcpy() function

  • Syntax:

char* strcpy(char* dest, const char* src);

  • Description: The strcpy() function copies the string pointed by source

(including the null character) to the character array destination.

  • Parameters:
  • dest − This is the pointer to the destination array where the content is to be copied.
  • src − This is the string to be copied.
  • Return Value
  • This returns a pointer to the destination string dest.

23

slide-24
SLIDE 24

What is the output here

#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

slide-25
SLIDE 25

What is the output here?

#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

slide-26
SLIDE 26

What is the output here

#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

slide-27
SLIDE 27

memcopy() Function

  • Copies n characters from memory area str2 to memory area str1.
  • Function prototype:

void *memcpy(void *str1, const void *str2, size_t n)

  • str1: pointer to the destination array where the content is to be copied
  • str2: This is pointer to the source of data to be copied
  • n: number of bytes to be copied
  • Return Value

This function returns a pointer to destination, which is str1.

slide-28
SLIDE 28

strcpy() vs. memcpy()

  • strcpy() function copies the string pointed to by source to destination.

and return the pointer to the destination string.

  • memcpy() function copies n characters from the object pointed to by

s2 into the object pointed to by s1. It returns a pointer to the destination.

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);

slide-29
SLIDE 29

Example

#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

slide-30
SLIDE 30

You can deal with them like normal variables

#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

slide-31
SLIDE 31

Also in Arrays

#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

slide-32
SLIDE 32

Also in Structures

#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

slide-33
SLIDE 33

Also array of structures

#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

slide-34
SLIDE 34

Summery

  • The C dynamic memory allocation functions are defined in

stdlib.h header.

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