From the course: C Standard Library

Memory allocation - C Tutorial

From the course: C Standard Library

Start my 1-month free trial

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.

Contents