Lec04 C Memory Management, Usage
Lec04 C Memory Management, Usage
1
Administrivia...
Computer Science 61C Fall 2021 Wawrzynek and Weaver
fi
Reminder: Remember What We Said Earlier About
Buckets of Bits?
Computer Science 61C Fall 2021 Wawrzynek and Weaver
3
fi
ff
And so for pointers...
Computer Science 61C Fall 2021 Wawrzynek and Weaver
• Declaring pointers
• int a; /* An integer value */
int *p; /* A pointer to an integer */
char **q; /* A pointer to a pointer to a character */
• Getting the address of a variable/value
• p = &a;
• Getting or setting the value held at a pointer
• a = *p;
*p = a;
• And pointer arithmetic & arrays:
• p[10];
*(p + 10); /* Since sizeof(int) == 4, the actual address is 40 + p */
4
C Memory Management
Computer Science 61C Fall 2021 Wawrzynek and Weaver
Stack Animation
Computer Science 61C Fall 2021 Wawrzynek and Weaver
stack
• Last In, First Out (LIFO) data structure
main ()
{ a(0); Stack
Stack Pointer
} grows
void a (int m) down
{ b(1);
} Stack Pointer
void b (int n)
{ c(2);
} Stack Pointer
void c (int o)
{ d(3);
} Stack Pointer
void d (int p)
{
} Stack Pointer
9
Managing the Heap
Computer Science 61C Fall 2021 Wawrzynek and Weaver
• sizeof returns size of given type in bytes, necessary if you want portable code!
11
)
Observations
Computer Science 61C Fall 2021 Wawrzynek and Weaver
ff
When Memory Goes Bad:
Writing o the end of arrays...
Computer Science 61C Fall 2021 Wawrzynek and Weaver
• EG...
• int *foo = (int *) malloc(sizeof(int) * 100);
int i;
....
for(i = 0; i <= 100; ++i){
foo[i] = 0;
}
• Corrupts other parts of the program...
• Including internal C data used by malloc()
19
When Memory Goes Bad:
Freeing the Wrong Stu ...
Computer Science 61C Fall 2021 Wawrzynek and Weaver
20
ff
When Memory Goes Bad:
Double-Free...
Computer Science 61C Fall 2021 Wawrzynek and Weaver
• EG...
• struct foo *f = (struct foo *) malloc(sizeof(struct foo) * 10);
...
free(f);
...
free(f);
• May cause either a use after free (because something else
called malloc() and got that address) or corrupt
malloc's data (because you are no longer freeing a pointer
called by malloc)
21
And Valgrind...
Computer Science 61C Fall 2021 Wawrzynek and Weaver
• getc/getchar
• Read single characters... Note return type!
• gets/fgets
• Read strings up to a linefeed...
• Note danger of gets(): it will write however much it wants to!
• printf/fprintf
• Formatted printing functions
• scanf/fscanf
• Formatted data input functions: Need to take pointers as argument
• e.g.
int i;
scanf("%i", &i);
25
C unions
Computer Science 61C Fall 2021 Wawrzynek and Weaver
• We’ve seen how structs can hold multiple elements addressed by name…
• But what if you want to hold di erent types in the same location?
• union fubar {
int a;
char *b;
void **c;
} Fubar;
• Accessed just like a struct, but…
• Fubar *f = (Fubar *) malloc(sizeof(union fubar))…
f->a = 1312;
f->b = “baz”
• They are actually the same memory! It is just treated di erently by the compiler!
• Enough space for the largest type of element
26
ff
How to Use Unions…
Computer Science 61C Fall 2021 Wawrzynek and Weaver
• Well, you also have to know what the type is… Because C won't do it for you
• Common pattern
• enum FieldType {a_type, b_type, c_type};
union bar {
char *a;
int b;
float c;};
struct foo {
FieldType type;
union bar data; };
…
struct foo *f;
…
switch(f->type){
case a_type:
printf(“%s\n”, f->data.a); break;
27
Structure Layout In
Memory
Computer Science 61C Fall 2021 Wawrzynek and Weaver
28
Alignment, Packing, & Structures…
Computer Science 61C Fall 2021 Wawrzynek and Weaver
• struct foo {
int a; /* At 0 */
char b; /* At 4 */
short c; /* At 6 */
char *d; /* At 8 */
char e;}; /* At 13 */
• For the class we assume no reordering of elds
• But sizeof(struct foo) == 16!
• Need to add padding to the end as well, so that if we allocate two structures
at the same time it is always aligned!
31
Pointer Ninjitsu:
Pointers to arrays of structures
Computer Science 61C Fall 2021 Wawrzynek and Weaver
• Can assign to it
• f = &foo
• Create a reference to function foo
35
Managing the Heap
Computer Science 61C Fall 2021 Wawrzynek and Weaver
36
How are Malloc/Free implemented?
Computer Science 61C Fall 2021 Wawrzynek and Weaver
37
Simple Slow Malloc Implementation
Computer Science 61C Fall 2021 Wawrzynek and Weaver
Free Space
Malloc library creates linked list of empty blocks (one block initially)
Object 1 Free
First allocation chews up space from start of free space
Free
After many mallocs and frees, have potentially long linked list of odd-sized blocks
Frees link block back onto linked list – might merge with neighboring free space
38
The Problem Here:
Fragmentation
Computer Science 61C Fall 2021 Wawrzynek and Weaver
39
Faster malloc implementations
Computer Science 61C Fall 2021 Wawrzynek and Weaver
40
fi
Power-of-2 “Buddy Allocator”
Computer Science 61C Fall 2021 Wawrzynek and Weaver
41
Malloc Implementations
Computer Science 61C Fall 2021 Wawrzynek and Weaver
• All provide the same library interface, but can have radically di erent
implementations
• Uses headers at start of allocated blocks and/or space in unallocated
memory to hold malloc’s internal data structures
• Rely on programmer remembering to free with same pointer returned
by malloc
• Alternative is a "conservative garbage collector"
• Rely on programmer not messing with internal data structures
accidentally!
• If you get a crash in malloc, it means that somewhere else you wrote o the end of an array
42
Conservative Mark/Sweep
Garbage Collectors
Computer Science 61C Fall 2021 Wawrzynek and Weaver
void foo() {
pi = malloc(8*sizeof(int));
…
free(pi);
} The rst malloc of pi
leaks
void main(){
pi = malloc(4*sizeof(int));
foo();
… }
47
fi
Re ection on Memory Leaks
Computer Science 61C Fall 2021 Wawrzynek and Weaver
51
Faulty Heap Management
Computer Science 61C Fall 2021 Wawrzynek and Weaver
• void FreeMemX() {
int fnh[3] = 0;
...
free(fnh); Can't free memory allocated on the stack
}
• void FreeMemY() {
int *fum = malloc(4 * sizeof(int));
free(fum+1); Can't free memory that isn't the pointer from malloc
...
free(fum);
...
free(fum); Can't free memory twice
}
52
Using Memory You Haven’t Allocated
Computer Science 61C Fall 2021 Wawrzynek and Weaver
void StringManipulate() {
const char *name = “Safety Critical"; sizeof(char) is 1
char *str = malloc(10); but should have sizeof as a
strncpy(str, name, 10); good habit
str[10] = '\0'; Write off of the end of the array!
printf("%s\n", str);
}
53
Using Memory You Don’t Own
Computer Science 61C Fall 2021 Wawrzynek and Weaver
result[++i] = '\0'
Returning a pointer to
return result
}
stack-allocated memory!
54
}
void main(void)
char *str = "abc"
muckString(str) Pointing to a static string...
puts(str)
Ruh Roh...
56
}
58
Using Memory You Don’t Own
Computer Science 61C Fall 2021 Wawrzynek and Weaver
• struct UnitedFlyer{
...
char lastname[16];
char status[32];
/* C will almost certainly lay this out in memory
so they are adjacent */
...
};
...
void updateLastname(char *name, struct UnitedFlyer *f){
strcpy(f->lastname, name);
}
60
fl
So what...
Computer Science 61C Fall 2021 Wawrzynek and Weaver