Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!
Scott Rixner
Memory Allocation
Needed for systems programming
Inconvenient for application programming
Necessary to understand
Most machines view storage cells as bytes^ •
May also view storage cells as words
Scott Rixner
Memory Allocation
Allocated = memory space reserved
When do we know the size to allocate?
When do we allocate?
Compile-time (
static
)
Run-time (
dynamic
)
Scott Rixner
Memory Allocation
Will they point to already allocated memory (what we’veseen so far)?
-^
Will new memory need to be allocated (we haven’t seen thisyet)?
char
c;
int
array[10];
char
*c; int
*array;
Scott Rixner
Memory Allocation
Arrays
≈
pointers to the initial (0th) array element
i^
could point to an array, as well
May change over the course of the program
calloc
zeros allocated memory (otherwise, same
as
malloc
)
Statically allocatesspace for 2 pointers
Dynamicallyallocates space for data
Scott Rixner
Memory Allocation
For brevity, won’t in class
Textbook uses capitalization convention^ •
-^
int
a^
(int
malloc(num_items
if
(a
fprintf(stderr,“Out
of
memory.\n”);
exit(1); }
Scott Rixner
Memory Allocation
Some local variables:
int
f(…) {
static
int
value;
} int
main() {
Scott Rixner
Memory Allocation
0xFFFFFFFF 0x
0xFFBEC000 0xFF3DC000 0x
Scott Rixner
Memory Allocation
Must also deallocate it explicitly (using
free()
)!
Not automatically deallocated (garbage collected)as in Scheme & Java
Forgetting to deallocate leads to memory leaks &running out of memory
int
*a
(int *)
malloc(num_items
sizeof(int));
… free(a);… a^
(int
malloc(
num_items
sizeof(int));
Scott Rixner
Memory Allocation
If data structure is used until program termination,don’t need to free
Entire process’ memory is deallocated
Bad assumption
Scott Rixner
Memory Allocation
Date
*today; today
create_date3(9,
use
“today”
... return; }
Scott Rixner
Memory Allocation
Date
*today; today
create_date3(…);
use
“today”
... free(today);return; }
voidfoo(){
Date
*today; today
create_date3(…);
use
“today”
... destroy_date(today);return; }
Scott Rixner
Memory Allocation
*j = f()
Leads to referencing deallocated memory
Behavior depends on allocation pattern
int
*make_array(…) {
int
array[10];
… return
array;
int
*f(…) {
int
i;
… return
&i;
Scott Rixner
Memory Allocation
Upon return, space for local pointer variable isdeallocated
But the
malloc
-ed space isn’t deallocated until it is
free
-d
Potential memory leak if caller is not careful, aswith create_date3…
int *f(…) {
int *i_ptr =
(int *) malloc(sizeof(int)); … return i_ptr; }
int *make_array(…) {
int *array =
(int *) malloc(10 * sizeof(int)); … return array; }