Lecture 26: Memory allocation (cont); A custom string type
Overview
Burton Ma explains C dynamic memory allocation with `calloc`, `realloc`, and `free`, then applies those tools to building a mutable string type. The design stores a character pointer, string length, and buffer capacity in a struct, using constructor-like functions to allocate and copy strings while highlighting null terminators, ownership, and object lifetimes.
Key takeaways
- `calloc(n, size)` both allocates `n` elements and zeroes the allocated bytes, while `malloc` leaves the bytes uninitialized.
- `realloc` must receive a pointer to a dynamically allocated block; storing its return value in a temporary allows the caller to handle allocation failure without losing the original pointer.
- A C string's null terminator encodes its endpoint, so `strlen` takes O(n); storing the length in a custom string struct makes length lookup O(1).
- A mutable string struct needs a data pointer, a length, and a capacity, with capacity of at least `length + 1` to reserve space for the null terminator.
- A dynamically allocated string owns both its struct and its character buffer; free the buffer before freeing the struct, and never pass automatic local arrays to `free`.
Chapters
- `calloc(n, size)` allocates space for `n` elements and calculates the total size.
- Unlike `malloc`, `calloc` sets every allocated byte to zero, so an allocated integer array begins with zeroed elements.
- A zeroed character buffer begins with a null byte, which represents an empty C string.
- Choose `calloc` when zero-initialized bytes are useful; use `malloc` when initialization is unnecessary.
- `realloc(ptr, new_size)` resizes memory originally returned by `malloc`, `calloc`, or `realloc`.
- It preserves existing contents up to the available old or new size and may move the block or expand it in place.
- When shrinking a block, `realloc` can reduce its allocation without needing to copy the retained bytes.
- The returned pointer identifies the resized allocation, so code must use that result after a successful call.
- The example first allocates five bytes for `sys` and its terminating null byte.
- Appending `220` requires eight bytes total: seven visible characters plus the null terminator.
- The example stores the `realloc` result in a temporary pointer, checks for failure, then assigns it back to the string pointer.
- The original `sys` contents, including the terminator, remain available after resizing, allowing the longer string to be formed.
- Call `free` once for each dynamically allocated block; freeing the same pointer twice can cause undefined behavior.
- Setting a pointer to `NULL` after freeing it can help avoid accidentally freeing that pointer again.
- C strings use a null terminator because C arrays do not store their own lengths; finding a string's length therefore takes O(n) time.
- Burton Ma contrasts C strings with Java and Python strings and introduces a mutable string type implemented with a C struct.
- The proposed string struct stores a `size_t` length, a capacity, and a pointer to dynamically allocated character data.
- Length counts visible characters, while capacity records how many characters the buffer can hold.
- The buffer needs at least `length + 1` bytes to include the null terminator.
- Extra capacity, such as 16 bytes for a shorter string, lets the string grow without reallocating on every append.
- The manual example allocates memory for the string struct and separately allocates its character buffer.
- It uses `sprintf` to place `sys220` in the buffer and then sets the stored length to seven.
- Cleanup must free the character buffer before freeing the struct that contains its pointer.
- This manual approach works but requires callers to coordinate the buffer, length, capacity, and allocations themselves.
- A local automatic array cannot safely serve as a string's persistent data buffer because it ceases to exist when its function returns.
- Passing such a local array to `free` is invalid because only memory from `malloc`, `calloc`, or `realloc` may be freed.
- The proposed constructor-like functions hide allocation and bookkeeping behind operations such as creating an empty string or copying a C string.
- This abstraction reduces the work required of callers to maintain string invariants and release memory correctly.
- The empty-string constructor allocates a struct, sets its length to zero, and chooses a small initial capacity of eight.
- It allocates the character buffer with `calloc`, providing the zero byte needed to represent an empty C string.
- The function returns a pointer to the initialized struct, combining allocation with constructor-like initialization.
- Burton Ma compares this pattern to Java's `new` expression followed by constructor setup.
- The C-string constructor accepts a `const char *`, indicating that it will not modify the caller's source string.
- It determines the source length with `strlen` and allocates at least that length plus one byte for the terminator.
- The example uses `strcpy` to copy the source into the new buffer, with `memcpy` mentioned as an alternative.
- The repeated allocation and initialization steps across constructors motivate refactoring shared work into a helper function.
- The copy function accepts a `const` pointer to an existing string and copies its length and capacity into a newly allocated struct.
- It allocates a separate data buffer and uses `strcpy` to copy the null-terminated character contents.
- Separate buffers ensure the new string owns its copied data rather than sharing the source string's allocation.
- The repeated setup across the three constructor-like functions is another opportunity to extract common allocation logic.
Transcript excerpt
0:01 All right. Good afternoon, everybody. So we're just going to pick up from where we left off in the last class. So remember in the last class, we were talking about dynamic memory allocation. Uh and we saw how to use malloc. Right? So remember malloc lets you allocate a block of memory. You specify how big a block of memory you want. So if you want to store n items of some size, right? You call malloc with n times size of. There's a closely related function called calloc. Uh now malloc, you can probably guess stands for memory allocation, which is probably true. Calloc, no one actually remembers what the c is for. Um but it's called calloc. The way you use it is slightly different. Um you ask for you tell calloc how many items you want.
0:50 So here I want n items and you tell it how big each item is. So calloc will do this multiplication for you. Right? Calloc also has another side effect. Uh so uh it sets all the bits of the allocated memory to zero. Right? Malloc is uh uninitialized. And Whoops. Uninitialized. Right? So malloc gives you back a chunk of memory. There could be something in that memory already. Calloc sets everything to zero. Uh so what this means is that um if you treat
1:37 uh the memory returned by calloc as an array of some kind of integer type, all of your ints are zero. If it's a floating point type, they're all equal to 0.0. Uh and if they're a character array, then all of your strings are the empty strings. Right? Sorry, then your string is the empty string. Right? Because it's set to zero, that's like having the null terminator in the first uh element of the array, which is
This is the start of the transcript. Save this video free for the whole transcript, searchable and time-coded.
In this course
Related notes
Summary, takeaways, and chapters were generated by AI from the video's transcript and may contain errors. The video belongs to its creator, Burton Ma.