Зміст курсу
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
#include <stdio.h> #include <stdlib.h> // new header file! int main() { int* pX = (int*)malloc(sizeof(int)); printf("Address of allocated memory: %p\n", pX); return 0; }
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
#include <stdio.h> #include <stdlib.h> int main() { int* pX = (int*)malloc(sizeof(int)); *pX = 100; printf(" Value %d at address %p\n", *pX, pX); return 0; }
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
#include <stdio.h> #include <stdlib.h> int main() { int* pX = (int*)malloc(sizeof(int)); *pX = 100; printf(" Value %d at address %p\n", *pX, pX); free(pX); printf("After `free()` value %d at address %p\n", *pX, pX); return 0; }
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
#include <stdio.h> #include <stdlib.h> int main() { int* pX = (int*)malloc(sizeof(int)); *pX = 100; printf("Value %d at address %p\n", *pX, pX); free(pX); pX = NULL; return 0; }
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.
Дякуємо за ваш відгук!