Anda di halaman 1dari 16

CS F111 Computer Programming 1st Sem.

2011-2012

Agenda Dynamic Memory Allocation - Need for Dynamic Allocation - Dynamically Allocated Lists - Pointers, Allocation, De-allocation

Sundar B.

CSIS, BITS Pilani

11/12/2011

Dynamic Lists

Consider the problem of an address book (in your mobile phone or in your email client such as Outlook or Thunderbird): The size of the address book is not known ahead of time. So, a declaration of the form ABookEntry addressBook[MAX_SIZE]; is not good: If MAX_SIZE is very large you may waste space If MAX_SIZE is small, then you may soon find the address book overflowing. Thus the limitation is this: Allocation for this array is done once (and for ever).
2 Sundar B. CSIS, BITS Pilani 11/12/2011

Dynamic Lists

What we need is a model of allocation on the following lines: allocate some amount of memory for the list as and when it is full (or about to be full) allocate more and extend the list. Thus, what we need is a way to allocate memory on need i.e. when the program is running i.e. dynamically! Such lists are referred to as dynamically allocated lists (or dynamic lists). Arrays in C are static or semi-static (i.e. size is fixed and they are allocated once).

Sundar B.

CSIS, BITS Pilani

11/12/2011

Dynamic Allocation in C

In C, one can allocate memory dynamically by using pointers as follows: /* Assume ABookEntry has been defined. */ ABookEntry *AddressBook; /* AddressBook is a pointer to one or more ABookEntry values */ AddressBook = (ABookEntry *) malloc(MAX * sizeof(ABookEntry));
An expression of the form (T) e is a type conversion expression (or type-cast expression) that evaluates e and converts the value into type T . In particular an expression of the form (T *) A converts the array A of bytes of size N into an array of T of size N/sizeof(T)
4 Sundar B.

malloc is a library procedure that requests the operating system for memory. malloc(N) allocates N contiguous bytes of memory malloc returns an array of bytes
CSIS, BITS Pilani 11/12/2011

Dynamic allocation in C
Once allocated, a dynamic list can be treated like an array in every other sense i.e. AddressBook[j] will refer to the jth location in the array. as illustrated in the following code fragment: /* Assume ABookEntry has been defined as a struct with several fields including mobNum */

#define MAX 100 ABookEntry *AddressBook; AddressBook = (ABookEntry *) malloc(MAX * sizeof(ABookEntry)); AddressBook[0].mobNum = 9988776655; AddressBook[MAX-1].mobNum = 987654321;
5 Sundar B. CSIS, BITS Pilani 11/12/2011

Dynamic Allocation in C

A call to malloc may fail to allocate memory in particular the system may have run out of memory to allocate to your program. In this case malloc returns NULL which is a pointer (of any type) pointing to nowhere So, one must test every call to verify whether the allocation has succeeded. For instance: ABookEntry *AddressBook; AddressBook = (ABookEntry *) malloc(MAX * sizeof(ABookEntry)); if (AddressBook != NULL) { AddressBook[0].mobNum = 9988776655; AddressBook[MAX-1].mobNum = 987654321; }
6 Sundar B. CSIS, BITS Pilani 11/12/2011

Dynamic Allocation in C

// Read a list of mobile numbers

int MAX=100; ABookEntry *AddressBook; int j=0, MobileNum mn; AddressBook = (ABookEntry *)malloc(MAX*sizeof(ABookEntry)); scanf(%lu,&mn); realloc(ptr, N) adjusts the size of while (mn != -1) { the array addressed by ptr to N if (j==MAX) { resize the array to size MAX elements (of the same type); If N is larger than the previous size MAX *= 2; the array is extended without realloc(AddressBook, MAX); changing the content (that was } previously stored); AddressBook[j++].mobNum = mn; If N is smaller the array is shrunk scanf(%lu, &mn); without changing the content that } was stored in the part left after
shrinking);
7 Sundar B. CSIS, BITS Pilani 11/12/2011

Dynamic Allocation in C
A call to realloc may fail to allocate additional memory (if it is a call to extend). So the code fragment in previous slide must be rewritten as: int MAX=100, j=0, MobileNum mn; ABookEntry *AddressBook; AddressBook = (ABookEntry *)malloc(MAX*sizeof(ABookEntry)); scanf(%lu,&mn); while (mn != -1) { if (j==MAX) { MAX *= 2; if (realloc(AddressBook, MAX) == NULL) break; } AddressBook[j++].mobNum = mn; scanf(%lu, &mn); } if (mn != -1) handleMemoryError();

8 Sundar B. CSIS, BITS Pilani 11/12/2011

Memory Allocation in C

The memory allocation model we have studied so far is static or semi-static: there are separate areas for code and data data can be global or local memory for all global variables is allocated statically i.e. before program execution begins and addresses are known at compile-time memory for each local variable is allocated each time the enclosing function / procedure is called.

Sundar B.

CSIS, BITS Pilani

11/12/2011

Memory Allocation in C

Memory allocation for each local variable: an address for a local variable is of the form (fun_addr, var_addr) where var_addr is relative and decided at compile-time fun_addr is decided when the function / procedure is called when a function / procedure is called a call frame is pushed on the call stack deciding the fun_addr for that call the call frame has space for all local variables (including parameters) and their addresses are pre-defined when the function / procedure returns the call frame is popped (i.e. deleted) off the stack
10 Sundar B. CSIS, BITS Pilani 11/12/2011

Memory Allocation in C

Memory allocation done by malloc: is done in a separate area called the heap Memory allocated in the heap is not automatically recovered (until a program terminates) So if and when an allocated block is not needed you must recover it. and if you are allocating memory repeatedly, then you must keep track of the allocated / available memory. How do you recover allocated memory? Using a library procedure named free [will be discussed later]
11 Sundar B. CSIS, BITS Pilani 11/12/2011

Dynamic Allocation in C Example - Code


/* addbook.c */ #include <stdio.h> #include <string.h> #include <malloc.h> typedef unsigned long int PhoneNumber; typedef struct { struct { char first[32]; char middle[32]; char last[32]; } name; PhoneNumber phone; char email[64]; } ABookEntry; unsigned int bookSize = 100;

/*

malloc.h is the header file for the memory allocation library, which will get implicitly linked during compilation.
*/

12

Sundar B.

CSIS, BITS Pilani

11/12/2011

Dynamic Allocation in C Example - Code


/* addbook.c */ #include <stdio.h> #include <string.h> #include <malloc.h> typedef unsigned long int PhoneNumber; typedef struct { struct { char first[32]; char middle[32]; char last[32]; } name; PhoneNumber phone; char email[64]; } ABookEntry; unsigned int bookSize = 100;

int main() { ABookEntry *aBook; int j=0; PhoneNumber mn; aBook = (ABookEntry *)
malloc(bookSize * sizeof(ABookEntry));

if (aBook == NULL) handleError(); // Read records terminated by a 0 scanf(%lu, mn); while (mn!=0) { aBook[j].phone = mn; scanf(%s, &(aBook[j].name.first)); scanf(%s, &(aBook[j].name.middle)); scanf(%s, &(aBook[j].name.last)); scanf(%s, &(aBook[j].email)); j++; scanf(%lu, &mn); } }
CSIS, BITS Pilani 11/12/2011

13

Sundar B.

Dynamic Allocation in C Example - Code


/* addbook.c */ #include <stdio.h> #include <string.h> #include <malloc.h> typedef unsigned long int PhoneNumber; typedef struct { struct { char first[32]; char middle[32]; char last[32]; } name; PhoneNumber phone; char email[64]; } ABookEntry; unsigned int bookSize = 100;

int main() { ABookEntry *aBook; int j=0; PhoneNumber mn; aBook = (ABookEntry *)
malloc(bookSize * sizeof(ABookEntry));

Should the array sizes for names and email be fixed?


14 Sundar B.

if (aBook == NULL) handleError(); // Read records terminated by a 0 scanf(%lu, mn); while (mn!=0) { aBook[j].phone = mn; scanf(%s, &(aBook[j].name.first)); scanf(%s, &(aBook[j].name.middle)); scanf(%s, &(aBook[j].name.last)); scanf(%s, &(aBook[j].email)); j++; scanf(%lu, &mn); } }
CSIS, BITS Pilani 11/12/2011

Dynamic Allocation in C Example - Code


/* addbook.c */ #include <stdio.h> #include <string.h> #include <malloc.h> typedef unsigned long int PhoneNumber; typedef struct { struct { char *first; char *middle; char *last; } name; PhoneNumber phone; char *email; } ABookEntry; unsigned int bookSize = 100;

Use pointers for names and email!


15 Sundar B. CSIS, BITS Pilani 11/12/2011

Dynamic Allocation in C Example - Code


/* addbook.c */ #include <stdio.h> #include <string.h> #include <malloc.h> typedef unsigned long int PhoneNumber; typedef struct { struct { char first[32]; char middle[32]; char last[32]; } name; PhoneNumber phone; char email[64]; } ABookEntry; ABookEntry *aBook; unsigned int bookSize = 100; #define BUFSIZE 256 char buf[BUFSIZE];
16 Sundar B.

int main() { int j=0; PhoneNumber mn; aBook = (ABookEntry *)


malloc(bookSize * sizeof(ABookEntry));

if (aBook == NULL) handleError(); scanf(%lu, mn); while (mn!=0) { aBook[j].phone = mn; scanf(%s, buf);
aBook[j].name.first = (char *)malloc(1+strlen(buf)); strcpy(aBook[j].name.first, buf);

/* Repeat prev. 3 lines for middle and last */ scanf(%s, buf);


aBook[j].email = (char *)malloc(1+strlen(buf)); strcpy(aBook[j].email, buf);

j++; scanf(%lu, &mn); }}


CSIS, BITS Pilani 11/12/2011

Anda mungkin juga menyukai