cs415 systems programming
play

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


  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

  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

  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

  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

  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

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

  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

  8. “malloc” or “memory allocation” 4 bytes int *ptr = (int *) malloc (5 * sizeof(int)); A large 20 bytes memory block is ptr = Dynamically allocated to ptr 20 bytes of memory 8

  9. 9

  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

  11. “ calloc ” or “contiguous allocation” 4 bytes int *ptr = (int *) calloc (5, sizeof(int)); 4 bytes 5 blocks of 4 bytes each is 0 ptr = 0 0 0 0 Dynamically allocated to ptr 20 bytes of memory 11

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

  13. 13

  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

  15. “ realloc ” or “re - allocation” 4 bytes int *ptr = (int *) malloc (5 * sizeof(int)); A large 20 bytes memory block is ptr = Dynamically allocated to ptr 20 bytes of memory ptr = realloc (ptr, 10 * sizeof(int)); The size of ptr is changed from 20 ptr = bytes to 40 bytes dynamically 15 40 bytes of memory

  16. 16

  17. 17

  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

  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)); 1 st element of the allocated memory A[0] =8; 3 rd element of the allocated memory *(A+2) =3; 4 th element of the allocated memory A[3] =9; 19

  20. 20

  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 21 The Compiler would say….

  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

  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

  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 }

  25. What is the output here? #include <stdio.h> #include <stdlib.h> String = tutorialspoint, Address = 355090448 String = tutorialspoint.com, Address = 355090448 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); } 25

  26. What is the output here #include <stdio.h> /* suppose you want to store bigger description */ #include <stdlib.h> description = realloc( description, 100 * sizeof(char) ); #include <string.h> int main() { if( description == NULL ) { fprintf(stderr, "Error - unable to allocate required char name[100]; memory\n"); char *description; } else { strcpy(name, "Zara Ali"); strcat ( description, “Students of CS415"); /* allocate memory dynamically */ } description = malloc( 30 * sizeof(char) ); printf("Name = %s\n", name ); if( description == NULL ) { fprintf(stderr, "Error - unable to allocate required memory\n"); printf("Description: %s\n", description ); } else { /* release memory using free() function */ strcpy ( description, “CS415 student."); free(description); } } Name = Zara Ali 26 Description: CS415 student.Students of CS415

Download Presentation
Download Policy: The content available on the website is offered to you 'AS IS' for your personal information and use only. It cannot be commercialized, licensed, or distributed on other websites without prior consent from the author. To download a presentation, simply click this link. If you encounter any difficulties during the download process, it's possible that the publisher has removed the file from their server.

Recommend


More recommend