Lecture 25: Strings (cont); Memory allocation
Overview
Burton Ma explains how C's `memcpy` and `memmove` copy bytes, then introduces dynamic memory management with `malloc`, `free`, and pointers. He demonstrates allocating memory for individual values and arrays using `sizeof`, returning allocated arrays from functions, and why allocation-size mistakes can appear to work while still causing bugs.
Key takeaways
- `memcpy` copies bytes and is not safe for overlapping source and destination ranges; `memmove` is the appropriate function for in-place shifts.
- Memory-allocation sizes are byte counts, so an array of `n` integers needs `n * sizeof(int)` bytes, and a seven-character C string needs eight bytes for its null terminator.
- In C, dynamically allocated memory remains available after the allocating function returns, but the program must eventually release it with `free`.
- Returning a dynamically allocated array is safe when the caller receives its pointer and manages its eventual deallocation; returning a local array's address is not.
- Incorrect allocation sizes can produce programs that appear to work before later accesses exceed the allocated block, making careful size calculations essential.
Chapters
- `memcpy(destination, source, count)` copies `count` bytes; it does not move memory.
- Copying four `int` values requires `4 * sizeof(int)`, while copying four `char` values requires only four bytes.
- Pointer offsets select subarrays or string positions, such as copying the four-character substring `that` over `what`.
- `memcpy` is not guaranteed to work when source and destination regions overlap; use `memmove` for that case.
- The array-removal example shifts elements after an index one position earlier, using `memmove` because the regions overlap.
- The byte count for shifting four `int` elements is `4 * sizeof(int)`, not simply four.
- `sprintf` formats output into a string, unlike `printf`, which writes to standard output.
- Ma notes that `sprintf` can perform tasks such as concatenating strings, but postpones its detailed discussion.
- C strings are arrays of `char`, so string-function examples also practice pointer arithmetic and array indexing.
- Unlike Java's `new` and automatic garbage collection, C programmers manage both allocation and deallocation.
- The lifecycle is to request memory, initialize it, use the object, and call `free` when finished.
- `malloc`, `calloc`, and `realloc` allocate or resize memory; `free` receives the pointer to the allocated block.
- Allocate one value with `malloc(sizeof(type))`, store the result in a matching pointer type, and dereference it to access the value.
- For a structure pointer, `s->x` accesses a field; it is equivalent to `(*s).x`, with parentheses required because of operator precedence.
- A string holding seven characters needs eight `char` slots to include the null terminator; Ma demonstrates filling the allocation with `strcpy`.
- A zero-size allocation is generally not useful, and a successful allocation still needs to be released with `free`.
- Allocate an array of `n` elements with `n * sizeof(element_type)` bytes, then use the returned pointer with array indexing.
- Ma demonstrates dynamically allocated arrays of three `int` values and three point structures with `x` and `y` fields.
- The pointer's declared type does not change how many bytes `malloc` allocated; treating a smaller block as a larger type can write beyond it.
- A function cannot safely return a pointer to its local array, because that array's lifetime ends when the function returns.
- One approach allocates an array with `malloc` and returns its pointer; the caller later frees it, potentially in a different function.
- Another approach passes the function a pointer to the caller's pointer, allowing the function to store the allocated address through a pointer-to-pointer parameter.
- Ma highlights a repeated size bug: allocating `length` bytes instead of `length * sizeof(int)` may appear to work until more array elements are used.
- `malloc`, `calloc`, or `realloc` can return a null pointer if an allocation fails; one common response is to report an error and exit with a failure status.
- Ma discusses differing operating-system behavior and cautions that a null-pointer check may not detect memory exhaustion on some systems.
- The lecture emphasizes that memory-allocation bugs can remain hidden even when a program appears to run correctly.
Transcript excerpt
0:00 I've jumped ahead a little bit. Uh, so I'm going to skip a few of the functions that are in the notebook. You can read about them on your own time if you want to. Um, they're just basically how to use functions in the in the string header file. Uh, but the two functions at the end of the notebook are more important. So there's the functions memcopy and memmove. Uh, so these are the two functions that you'll want to consider using if you want to copy a chunk of memory uh to another uh location. Neither function moves the memory, right? So neither function actually moves the bits in memory. They both perform a copy. Memcopy is what you want to use if your where you're copying the bits into does not overlap with where you're copying
0:47 them from. So we've seen this function before. Uh, you tell it where do you want to start copying from? So you pass it a pointer to the source memory location. Uh, you tell it where you'd like to copy the memory into. So you pass it a pointer to the destination memory location. And you tell it how many bytes would you like to copy. So that's this thing called count. Right. If you're copying arrays, you can copy an entire array into another array. You can copy part of an array into another array. Um, and you can copy parts of an array into parts of another array. Right? So uh they're very flexible functions, right? Their flexibility comes from uh the fact that they use pointers to specify where and uh from where you want to copy the memory from and where you'd like to copy the
1:34 memory to. So there's a fairly long uh example program here.
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.