Dynamic Memory
malloc reserves memory at run time and returns a pointer. Always check for NULL and always release memory with free when finished. Forgetting to free causes a memory leak, and using memory after freeing it is a serious bug.
Example
int n = 4;
int *arr = malloc(n * sizeof(int));
if (arr == NULL) return 1;
for (int i = 0; i < n; i++) arr[i] = (i + 1) * 10;
int total = 0;
for (int i = 0; i < n; i++) total += arr[i];
printf("%d\n", total);
free(arr);Result
100
Exercise
Release the memory.
(arr);Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.