Dynamic Memory Allocation in C – Its usefulness with examples

Dynamic Memory Allocation in C refers to manual memory management of variables through the use of several functions from the standard library (<stdlib.h>) such as malloc, realloc, calloc, free, etc.

If you are wondering what I meant by “Dynamic”, then just know for now that C has different types of memory management: Static, Automatic and Dynamic.

For instance, the moment you declare a variable, the program creates some memory required for storing the value of a variable of some data type, which it automatically releases when the variable is at the end of its scope. Consider the following example:

Here, the program releases the memory allocated for storing the element of a data type “int” when the program ends. This is an example of Automatic Memory Allocation (we will learn more about it later).

In this article, you will learn how you can use dynamic memory allocation in C programming language. Let’s first study the different types of memory management in C.

Static Memory Management

In this type of memory management, your variables are allocated in main memory at compile-time either on the stack or in other sections of your program.  You do not have to reserve extra memory for using them, but on the other hand, you lose control over the lifetime of this memory, i.e., a variable in a function is only there until the function finishes. Consider the following example:

Here the memory of our declared array “array” will be released upon the function termination; that is, once the function is finished doing its job!

Automatic Memory Management

In this type of memory management, variables are allocated on the stack upon entry into a block and exists for the duration of that block; that is, it come and go as functions are called and return.

Both of the above memory management requires that the size of the allocation must be compile-time constant.

Dynamic Memory Management

Dynamic memory allocation is a bit different. You now control the exact size and the lifetime of these memory locations. If you don’t free the allocated memory when it’s no longer necessary, you’ll run into memory leaks, which may cause your application to crash, and because of it you cannot allocate more memory at some point. Memory leaks can be very dangerous because the system may run out of memory. Consider the following example:

Here, the malloc function is used to perform an allocation of contiguous memory. To free this allocated memory, C provides free function.

Allocation functions

Standard library of C provides several functions for allocating the memory: malloc, calloc and realloc.  

malloc function allocates a block of size bytes of memory, but it doesn’t initialize the values; that is, you will get indeterminate values if you print the pointer values into your console screen.

calloc function allocates a block of memory for an array of num elements, each of them size bytes long, and initializes all its bits to zero.

realloc function reallocates a block of memory. Through it, you can change the size of the memory block that is already pointed to your pointer. It returns a void pointer, so you need to cast it to your data type. The first parameter is the pointer to previously allocated memory block.

In all of the above cases, we used free function to free the allocated memory.

The usefulness of Dynamic Memory Allocation in C

Dynamic Memory Allocation is needed in those circumstances when you need full control over the time the memory is released. Let’s learn its usefulness.

1) Dynamic Array Creation

The most basic usage of Dynamic Memory Allocation in C is the creation of “Dynamic” arrays; that is, the arrays that can change its length. Consider the following program:

2) Full Control of Memory

Through these allocation functions, you know for sure when the program is releasing the memory. It is very useful in things like concurrency control, and if you know what you are doing, then it can increase efficiency as well.

Summing Up

In this tutorial, we have learnt the following:

  • There are three types of memory management in C: Static, Automatic and Dynamic.
  • Dynamic Memory Allocation is necessary for creating Dynamic Arrays in C.
  • Manual Memory Management is required for the maximum efficiency in various algorithms.


Conclusion
 
C is a low-level programming language, mostly used for systems programming. This is manifested with the usage of dynamic memory allocation (manual memory management).

For simple tasks, such as, storing static values in an array, then you don’t need to use dynamic memory allocation, as it will only make the code harder to read and unsafe too.

In C++, manual memory management is done mostly through new and delete operators, so if you are using C++, then it is highly recommended to use C++ operators rather than resorting to use C functions.

Did this tutorial teach you something new you didn’t know before? Please let us know in the comments section below!

How To Add A Drop Down Menu On Tumblr

Click here to get to the step by step guide.

When I started designing / developing one of my Tumblr blogs, the very first thing that I wanted to do is to add a drop down menu that would list the pages on my projects, services, etc.

I’m one of those programmers who first search the solution of a problem on the internet before finding the solution myself. So, I googled “drop down menus in Tumblr” and found an excellent site, namely CSS MenuMaker, which provides the HTML/CSS/Javascript code of already created customizable menus! It is also a good basis for learning HTML/CSS/Javascript as you can play with the values to change the look of your menu.

In this post, I’m going to show you how easy it is to add a drop down menu on Tumblr blog. Let’s get started!

How To Add A Drop Down Menu On Tumblr

1) Getting the HTML/CSS/Javascript code

Go to the site, and select the menu that you like the most. I chose this for my blog, because its color is compatible with the theme of my blog, but you can choose any design you want.

2) Downloading the source code

Under the “Download Source” section, download the “source.zip” in your computer and extract the files in it. You will find three different files: styles.css, index.html and script.js for CSS, HTML and Javascript code respectively.

3) Copying the code to your customization section

Copy the CSS code from styles.css and paste it to your “Custom CSS” section in your Tumblr blog, and copy the HTML code from index.html (only copy <div id=’cssmenu’> section!) and paste it to your “Edit HTML” section, just after the title and description of your blog (this should be in the beginning of <body> tag). You need to change the name of pages and the references to them (Hint: <li class=’active’> is for drop down menu). Following is an example of how your code should look like:

Lastly, copy the Javascript code from script.js and paste it just before the </body> tag in “Edit HTML” section. Save the theme and open your blog in a different tab to test the drop down menu.

Do you use a different way to add a drop down menu on Tumblr blog? Tell me in the comments section below!

Properties in C#

Properties is a simple and yet useful feature of C# programming language. It basically enables a programmer to use object member syntax (i.e., object.methodname) for setters and getters functions. Through it, you can read, write, or compute the value of a private field very flexibly.

If you have used C++ or Java in the past, then you most likely have seen methods in a class for reading and writing member variables, such as “setLentgh(int length)” and “getLength()” for setting the length and getting the length respectively. In C#, properties are actually special methods called accessors.

In this tutorial, I will teach you how you can use properties feature in C# and I will show you the cases where it is very useful.

How do I use Properties in C#?

The following is the simple syntax for defining properties in a class:

Using the properties in a class is as easy as follows:

Now, we can easily use our class in a program, we can do so as follows:

As you can see, how easy it is to use this feature in C#. Now, the question that might arise in your mind: What good this feature does to us? (Except the fact that “_length” is renamed to “length” in use)

When should I use Properties in C#?

The place where properties come handy are those places where you need to implement member syntax for getting/setting a data from an array or struct, because without properties, you can only resort to implement setter and getter methods for that. For instance, suppose the following class “Vector3f” for holding three members: x, y, z:

But, you like to store the values of a vector in an array instead (probably because a programmer wants to do specialized operations internally, which can be done only on arrays such as SIMD operations for efficiency, etc.) along with the methods to set/get the x, y and z value from an array.Without properties feature, the class would look like the following:

With properties feature, you can simply implement the setters and getters for x, y and z values as properties. We can do so as follows:

Now you can use the class in a program, we can do so as follows:

Another very useful case of properties is when you want to implement something in setter / getter, yet you want to use properties as if you are accessing a variable instead. MSDN provided a great example of a class “TimePeriod” which stores a time period in seconds, but a property named “Hours” specify a time in hours and performs the conversion between hours and seconds.

Additionally, Properties can also be used to make some variables ‘read-only’. For instance, arrays in C# have a property “Length” (which gives the length of an array) that can only be read.

Summing Up

In this tutorial, we have learned the following:

  • Properties is a very useful feature of C#.
  • Using this feature in your C# code is a matter of writing setter / getter functions.

Conclusion

Properties in C# is one of the “killer” features of the language, because it makes the libraries / assemblies development and usage so easy. This feature encourages programmers to use C# for developing libraries for .NET framework instead of other programming languages, because no other similar static typed language has this feature.

What is your opinion on this feature? Let me know in the comments section below!

How to use Google’s Prettify to add syntax highlighting to code snippets

Click here to learn the faster way.

As this blog was going to have posts on programming (as obvious from the name of this blog and About page), I would most likely need to use code snippets as examples, because it isn’t fun to discuss about programming without any mention of source code. Despite the fact that not all programming blogs have syntax highlighting enabled for their code snippets, it is quite ugly in look to see the code without proper formatting and syntax highlighting.

With the use of Google’s JavaScript module called Prettify, you can easily highlight your code. The following is an example of how your code will look like when using this module:

The above example is the famous Hello, World program in C++. You can see that the code is highlighted in the fashion of vim text editor (more on that later).

So how can I use this awesome feature in my programming blog?

You simply need to copy the HTML/CSS/JavaScript code from the trunk of Prettify to your HTML page. To make sure you don’t end up copying the wrong code, I copied and pasted the required code (thanks to this post):

Paste the following before </header>:

Paste the following in the <style> tag:

Note: If you are using the Tumblr platform for your blog/site, then just copy the CSS code in your “Custom CSS”. Do not mess with the <style> tag in HTML customization page!

Once the library is properly installed, you can pre-format and highlight your code by simply writing the code snippets in <pre> and <code> blocks as follows:

You don’t need to specify the programming language; Google’s Prettify figures it out itself! The <pre> tag is for pre-formatting the code and <code> is for highlighting it, so make sure to use both <pre> and <code> tag when adding a source snippet in your post.

HTML Encoding

One thing that you need to keep in mind is that you must change all the angle brackets in your code to &lt; and &gt; which means you need to change all of your < to &lt; and > to &gt; in the code. I use this online encoder to encode my code to the proper HTML.

Themes

I use the Sunburst style, so the CSS code that I posted will give you the Sunburst style as well. I prefer this style because its look is similar to vim text editor, which I use as my default text editor on Linux, but you can use different themes for your own taste.

This procedure for adding syntax highlighting can be used anywhere the customization of HTML is available such as Tumblr. See this stand-alone HTML page example.

Faster way to load Google’s Prettify

Previously we hard coded the whole JavaScript and CSS for styling. The quickest way to add Google’s Prettify is to simply load run_prettify.js via one URL.

You need to specify the parameters; I specified lang parameter and skin parameter. Note that to use syntax highlighting with this method, you need use prettypink class.

See this stand-alone HTML page example.

Did this post teach you something you didn’t know before? Please let me know in the comments section below!

How to sleep the CPU through cross-platform sleep function in C/C++

If you need your CPU to sleep for a while; that is, wait for some time without any activity, then you need to call system functions in your program. For instance, if you want to show some text for 2 seconds, then you can sleep the CPU to simulate the effect.

Unfortunately, there is no cross-platform way to sleep the CPU; Windows provide sleep() function in <windows.h> header, which takes milliseconds in an argument, while Linux provides sleep() in <stdlib.h> function which takes seconds and usleep() which takes milliseconds in an argument.

To overcome this cross-platform problem, we will use macros to detect whether the code is compiling under Windows or Linux. Following is its implementation:

Now, you can call SLEEP with an argument of milliseconds for sleeping the CPU whether you are on Windows or Linux. Apart from that, you can also use rlutil::msleep() from rlutil library to get cross-platform sleep function.

rlutil – a cross-platform library to change console text color in C/C++

Dissecting the rlutil library to colorize the text.
Last month ago, while I was searching for cross-platform ways to change console text color in C++, something in the fashion of vim text editor, then I found a very good open-source library, called rlutil, which can be used to change console text color in console-based applications (vocabulary builders, text editors like vim, etc.) and for easing the creation of roguelike games.
It is cross-platform library, so your code can run on both Windows and Linux, and the effect will be the same; that is, your text will be colorized!

rlutil is a single header library and hosted on Github, so you can easily clone the source codes in your hard drive. I found the API of rlutil very easy to use; you do not need to compile the library; it is a single header file library, so just include the rlutil.h in your directory of source file and call simple functions to change the color of your text!

In this post, I will show you how you can change console text color through rlutil to add fun to your boring console programs. Let’s get started!

rlutil – a cross-platform library to change console text color in C/C++

Create a new folder “rlutil-test” and within the folder, create a new file “main.cpp” (the rlutil.h should be in the same directory as your main.cpp file so copy the file if you haven’t yet)

main.cpp

Assuming the file is saved as main.cpp , you can easily compile and run the program using g++ as follows:

My linux console shows the following:

rlutil example

You can see how easy it is to change the color of console text using rlutil library!

I have tested the code on both Linux and Windows and the result was the same. Note that if you are compiling through C compiler, then the library will automatically remove the namespaces, so you won’t need to write rlutil:: when using the functions.

Apart from functions for changing the color of console text, the library also has many utility functions such as rlutil::cls() for clearing the console screen, rlutil::anykey() to check if a user presses a key, rlutil::hidecursor() and rlutil::showcursor() for hiding and showing the cursor respectively, rlutil::msleep() for sleeping the CPU in a cross-platform way, rlutil::getkey() for reading the pressed keys, etc.

What do you think of this library? Does it provide a better API to change the console text color for console-based programs than the libraries you use?