dynamically allocated memory string cgs 3460, lecture 33 apr 3, 2006 hen-i yang
Post on 16-Dec-2015
214 Views
Preview:
TRANSCRIPT
Dynamically Allocated Memory String
CGS 3460, Lecture 33Apr 3, 2006Hen-I Yang
Previously… Dynamic Memory Allocation Dynamic Allocated Arrays
Agenda
Dynamic Allocated Arrays Dynamic Allocated Strings Deallocation Strings
Malloc an Array
int *a;a = malloc(n * sizeof(int)); Can we just say a = malloc(n* 4)?
Not a good idea After malloc, you have all the space neede
d for the array allocated After that, you can use a[i] or *(a+i) to acc
ess the elements
Calloc an Array
int *a;A = calloc(n, sizeof(int)); Why do we use calloc? All elements are i
nitialized to 0 at the time of allocation
Realloc an Array
int *a;a = malloc(n * sizeof(int));a = realloc(a, m * sizeof(int)); Why do we use realloc? So we can chang
e its size after we malloc or calloc If first argument is null, realloc = malloc If second argument is zero, the memory is
freed
Strings
In C, strings are equivalent to a collection (array) of characters
How do we setup a string? char quarterback[] = “Palmer”; 7 bytes are allocate for variable name. What if Mannings replaced Palmer as QB? char director[9]; Let’s say, a guy named Roethlisberger comes along. char * quarterback;
quarterback = (char *) malloc (15);
How do we use malloc with strings?
char * temp_buffer = (char *) malloc(20); char * name; char * title; scanf(“%s”, temp_buffer); name = (char *) malloc(strlen(temp_buffer)); strcpy(name, temp_buffer); strcpy(temp_buffer, “□ □ □ □…□”);
□ x 20 scanf(“%s”, temp_buffer); title = (char *) malloc(strlen(temp_buffer)); strcpy(title, temp_buffer);
Array of strings
If there are multiple strings, we can use a 2 dimensional array to store it.
But it waste too much space, instead we store an array of pointers to strings
char * strings[NUMBER_OF_STRINGS]; strings[0], strings[1], …
Recycle
Memory leak Freep = malloc(…);free(p);
Calling free to a memory location, not previously allocated dynamically (e.g. an element of array, a variable) can have unpredictable effect
Dangling pointer: refer to the pointer pointing to an address that is already freed
Some programmers put p = null; whenever they free the memory p points to.
Strings
String: an array of characters String constant (String literals) String variable
Summary
Dynamic Allocated Arrays Dynamic Allocated Strings Deallocation Strings
Before you go
Nothing for today. Enjoy your plan for tonight.
top related