From the course: C Standard Library
Memory allocation
- [Instructor] Pointers simply point to variables. Well more specifically the R variables that hold memory addresses, so creating a pointer is by no means a guarantee that it will point to valid data. A pointer may point to existing local or global variables. But you may also want to create new variables dynamically and assign their addresses to pointers. These new variables need some exclusive space in volatile memory and that's what a memory allocation function does. It reserves some space in memory for a new piece of data and this space will not be used for anything else while this space is reserved. Stdlib.h provides several memory allocation functions. Let me show you three. We have malloc, realloc, and free. Malloc allocates as many types as specified by its argument and it returns the address of this newly allocated space. Realloc resizes a previously allocated space pointed to by its first argument. The second argument is its new size. Because this may require additional space in an already packed memory, the whole data segment may be relocated so the original address of the pointer is not guaranteed to remain unchanged. The new address is returned. Finally the free function deallocates the space pointed by its argument, leaving it free for further allocations.
Practice while you learn with exercise files
Download the files the instructor uses to teach the course. Follow along and learn by watching, listening and practicing.
Contents
-
-
-
-
-
Memory allocation1m 32s
-
(Locked)
Memory allocation example2m 29s
-
(Locked)
Random number generation1m 48s
-
(Locked)
Random number generation example2m 40s
-
(Locked)
String conversion2m 11s
-
(Locked)
String conversion example6m 29s
-
(Locked)
Sort and search1m 52s
-
(Locked)
Sort and search main4m 50s
-
(Locked)
Sort and search functions5m 6s
-
(Locked)
Challenge: Let's get random1m 38s
-
(Locked)
Solution: Let's get random5m 40s
-
-
-
-