Lecture 4 - Memory Management PDF
Document Details
Uploaded by ReceptiveBalance4879
Tags
Summary
This document provides a lecture on memory management in C and Java, covering topics such as pointers, strings, and data lifetimes. It explains different memory allocation strategies and demonstrates the manual management of memory in C using functions like "malloc" and "free".
Full Transcript
Space: bytes in memory number/index of memory location is its address address value used as a pointer ○ references data occupying addressed location allocate space: assign location for data item to occupy can pass array name as a string ○ resolve...
Space: bytes in memory number/index of memory location is its address address value used as a pointer ○ references data occupying addressed location allocate space: assign location for data item to occupy can pass array name as a string ○ resolves to a pointer pointer allocates space from constant pool (readonly) ○ allocated on launch can use pointer as array ○ can use [] to index attempt to modify readonly memory results in a fault can declare pointer as constant ○ const means that the data being referred to is readonly ○ const char* cp = “nifty”; cp = ‘a’; uninitialized pointers have undefined value: could raise fault or could clobber Null pointers, wild pointers, faults not all numbers a valid address invalid pointer causes a fault (pointer value not valid address) wild pointer: pointer value is valid but not pointing to right space special pointer NULL guaranteed to segfault ○ easier to debug Strings strcat(dest_string, src_string) ○ concatenates source string onto destination string ○ #define N 16 void f() { char ca[N] = “nifty”; strcat(ca, “ish”); make sure enough space ○ not enough room results in buffer overflow could overwrite existing data ○ strn variants more safe ○ size_t an integer type for the length of something (bytes of space) Data lifetimes constants and static/globals live forever ○ code: function instructions ○ data: global variables locals die on return dynamic data: allocate space at runtime in stack, heap ○ stack for local variables and parameters ○ heap for dynamic memory explicitly allocated and released Heap Java deletes objects when not used anymore ○ garbage collection: deletes object if no references to it In C must manually use operators malloc and free ○ no builtin new() malloc returns raw void* pointer to allocated space (heap block) ○ must know how much space needed in bytes ○ must convert pointer to T* type ○ must free() space when done ○ void* malloc(size_t size) allocates block os space size bytes returns pointer (address) of that space returns NULL if allocation failed ○ myPtr = (int*) malloc(10 * sizeof(int));