Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Malloc and Free | Pointers
C Basics
course content

Зміст курсу

C Basics

C Basics

1. Introduction
2. Data
3. Operators
4. Control Statements
5. Functions
6. Pointers

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:

c

Main

copy
1234567891011
#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 the malloc() function.

To store data at the address provided by the malloc() function, we use the dereference operator.

c

Main

copy
123456789101112
#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:

c

Main

copy
1234567891011121314151617
#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.

c

Main

copy
1234567891011121314151617
#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.

Все було зрозуміло?

Секція 6. Розділ 4
We're sorry to hear that something went wrong. What happened?
some-alt