Зміст курсу
C Basics
C Basics
Malloc and Free
These functions enable us to create new objects not during compilation but during program execution, allowing us to use dynamic memory allocation.
malloc()
Before, to allocate memory for our data, we would simply declare:
Now, with the malloc()
function, we can allocate memory dynamically:
The malloc()
function requires the number of bytes to be allocated as its argument. If you're unsure of the byte size needed, but you know the type of data to be stored, you can adjust the expression like this:
What's next?
Notice that we're assigning the result of the malloc()
function to a pointer. This means malloc()
returns an address!
The prefix (int*)
is an explicit cast. We manually specify the desired type. For instance:
Main
Note
Remember to include the header file
stdlib.h
. It contains the prototype for themalloc()
function.
To store data at the address provided by the malloc()
function, we use the dereference operator.
Main
Is it possible to free up memory? – Yes, but only the memory allocated by malloc()
and similar functions.
free()
This function is used with pointers. To illustrate, let's expand on the example above:
Main
Interestingly, even after we "delete" a pointer, it remains functional, but the value stored in its associated memory location becomes garbled.
This leads to a problem: an occupied memory cell now holds unreliable data. To prevent these pointers, the used pointer should be reset to NULL
.
Main
Setting a pointer to NULL
after freeing its memory is a clear way to indicate that the pointer no longer references a valid memory location.
Always check if the pointer is NULL
before using it to ensure you're not accessing invalid or already allocated memory.
Все було зрозуміло?