Dynamic Memory Allocation is used to create arrays (and other variables) of variable size. There are 4 function for DMA: malloc, calloc, realloc and free.




Have you ever wondered how to add or remove elements to an array?

When you define an array, you set a fixed size, so how do you change that?

This is one of most common situations in which Dynamic Memory Allocation comes in handy.

A brief introduction to Dynamic Memory Allocation


As its name says, Dynamic Memory Allocation means changing the amount of memory assigned to a variable.

That definition isn’t much accurate, but it allows you to get the point. Read this by PC Magazine if you want

There are 4 functions to dynamically manage memory:

Function Description
malloc It allocates a block of memory for one object
calloc It allocates a block of memory for one or more objects
realloc It changes the amount of space assigned to a block
free It frees the memory assigned to a block

Those functions are all defined in stdlib.h, so remember to include that library:

A block is a group of one of more contiguous variables/elements.

An array is a block, because all its elements are allocated one after the other.

Memory blocks

It’s important to free the memory allocated dynamically, because it isn’t done automatically when the program closes – unlike variables defined normally.

If you don’t do it, you may end up draining all computer’s RAM.

Malloc


The function malloc allocates a memory block of size size and it returns a pointer to its first byte.

Syntax:

Where size is the amount of space – in bytes – to allocate.

The data type size_tthat we saw in the last post – is just an integral type defined in stdio.h.

As you can see, malloc returns a generic pointer ( void * ).

We’ve already talked about generic pointers in this article about data types.

Some compilers can convert it automatically to another data type, others requires an explicit cast:

You can also cast a specific type, but only if it’s compatible with the new one. However you sometimes lose some data during the conversion.

Examples:


  • void * is always fully compatible with other types of pointers, so you can cast it without worrying about losing any data.

  • int can’t hold floating-point numbers, but only integers, so during this conversion you’ll lose all the digits after the point.

  • float holds floating-point numbers, integers included, so during this conversion you won’t lose anything.

Calloc


The function calloc is almost identical to malloc, but there are two differences:

  • It allocates a block of size members*size.
  • It initialise each byte to 0.

Its syntax is:

These two lines below allocates the same amount of memory:

Therefore, the only one reason for choosing one instead of the other is the second point – calloc intialises each byte to 0.

Realloc


The function realloc resizes a block.

Its syntax is:

Where:

  • pointer is the pointer to the block you want to modify.
  • size is the new size of the block.

If size is greater than the block’s current size, all its bytes will remain unchanged and more memory will be added.

Otherwise, if size is less than the block’s current size, it will lose as many bytes at its end as the difference between the two sizes.

Free


Last but not least, the function free frees the memory allocated for a block, so that it can be used by other variables.

It requires only a pointer to a block to free:

Space allocated using malloc or calloc isn’t freed when the program closes, so don’t forget to use this function!

Let’s analyse today’s program!


Today’s program creates an array of 5 elements and it lets you add new elements, change their value or print them all.

DMA example

Since the program is quite long I’m going to explain only the most important parts – the ones which contains new functions – and sum up the rest.

int *array = malloc(sizeof(int)*current_size)

This line allocates an amount of memory equal to the size of int times current_size ( =SIZE=5 ) and then it assigns the first byte’s address to a pointer array.

initialise(array, 4, SIZE)

This is a custom function declared at the beginning of the code and defined at the end and its objective is to initialise each member of array.

It works thanks to the fact that malloc creates a single memory block, therefore each elements is next to the other and you can get them the same way you do for arrays and arrays’ pointers.

Options

After having initialised the array, the program shows the four possible options to the users and it enters a do…while loop, which ends only if the input ( option ) is 4.

The first case uses realloc, so we’re going to see it in detail later. It adds a new element to the array and it sets its value to one chosen by the user.

The second one changes the value of an existing element.

Finally, the third case prints all the elements, grouping them in lines of maximum LINE_LENGTH each.

realloc(array, (++current_size)*sizeof(int))

I’ve used realloc to add to array space for another element.

Look at the second parameter:

  • ++current_size increase current_size by 1 and returns its new value to the expression.

    If I had written current_size++ instead, the variable would be incremented anyway, but the expression will use its old value.

  • sizeof(int) simply gets the size in byte of int.
  • Multiplying this two values, we get the right amount of memory needed to contain one more int element ( the current amount of elements plus one times the space required for each ).

free(array)

This line is very important, because it frees the memory occupied by array: if you don’t do that, your computer won’t be able to use that part of memory until you shut down it.

If you make a program which allocates a big amount of space and after some time you notice that your RAM is filled up, I recommend you to try checking if you missed this function – and then restart you machine.

C and C++ comparison


Just like last time, also in this case the C++ version differs a lot: you should read this page by GeeksforGeeks to learn how to use vectors.

Anyway, I want to show you some of the functions I’ve used:

  • push_back, to add an element at the vector’s end.
  • begin and end, which return iterators for the first and the last element of the vector. Iterators are like pointers to elements of a vector.
  • clear, to empty the vector. It isn’t as important as free, because it doesn’t delete the block, but only its elements. In fact, the memory occupied by a vector is freed automatically.

Conclusion


Today you’ve learnt how to dynamically manage memory, so now you’ve got complete control over it.

Now you can definitively make complex programs.

This is the last post of the Learn C guide: of course there’s more, but what you’ve learnt here is, at least in my opinion, enough to be considered a mid-high level C programmer.

For example, you could learn 2D and 3D graphics in C, but I recommend you to not do it – trust me, because I did it for 2 years, before understanding that C isn’t made for that!

Furthermore, this blog isn’t a functions dictionary, but a guide for turning yourself into a real programmer, not by memory but by concepts.

Remember that the Internet is your best ally in your learning path and that this blog’s mission is far from over.

In fact, I’ll soon – probably (99%) next week – start a new guide – this time to learn Java – with a total new approach: not by concepts – because you’ve already learn all the fundamental ones – but by practice.

In short: you’ll easily learn a new language by writing fun programs and games.

Said so, why don’t you subscribe to the newsletter? You’ll get exclusive guides for things like useful algorithms or fun projects!

Comment if you have any doubt and share this to show your appreciation.

Anyway, the post is finished, have a good day and we will see next week!

From Zephyro it’s all, Bye!

Categories: Learn C

2 Comments

TutorialSpan · 2 April 2019 at 6:51 PM

Is there are any C++ tutorials on this website?

    Zephyro · 3 April 2019 at 1:10 PM

    Not yet. However, for each topic of the C guide there is a comparison between C and C++. There’s always a C++ version for each program and in some posts you can find it explained in a paragraph.

Leave a Reply

%d bloggers like this: