Docsity

Dynamic Memory Allocation in C: Dynamic Allocated Arrays and Strings, Study notes of Computer Science

Partial preview of the text

Download Dynamic Memory Allocation in C: Dynamic Allocated Arrays and Strings and more Study notes Computer Science in PDF only on Docsity!

Dynamically AllocatedMemoryStringCGS 3460, Lecture 33Apr 3, 2006Hen-I Yang

Previously… „^ Dynamic Memory Allocation „^ Dynamic Allocated Arrays

Malloc an Array int

*a; a^

=^ malloc(n

sizeof(int));

„^ Can we just say

a^

=^

malloc(n*

Not a good idea „ After malloc, you have all the spaceneeded for the array allocated „ After that, you can use a[i] or *(a+i) toaccess the elements

Calloc an Array int

*a; A^

=^ calloc(n,

sizeof(int));

„^ Why do we use calloc? All elements areinitialized to 0 at the time of allocation

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

Recycle „^ Memory leak „^ Free^ p = malloc(…);free(p); „^ Calling free to a memory location, not previouslyallocated dynamically (e.g. an element of array,a variable) can have unpredictable effect „^ Dangling pointer: refer to the pointer pointing toan 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

Before you go „^ Nothing for today. „^ Enjoy your plan for tonight.