×

Garbage in C

Garbage in C

The C programming language is a perfect fit for embedded systems as it provides low level control, structured programming, and portability. On the contrary, it does not provide any native garbage collection. Garbage collection is a mechanism that provides automatic memory reclamation for unused blocks of the memory. Developers and programmers dynamically allocate memory, but when a block is no longer needed, they do not return it to the system with a free() function call. Garbage collection considers such block by recognizing the unused memory and reallocates it back into the free memory area.

Garbage collection was introduced by John McCarthy in the year 1958 as a memory management mechanism of LISP language (List Processing Language). Other programming languages like Java, C#, python, and so on support garbage collection so that a programmer no longer has to free the memory explicitly.

There are numerous approaches to garbage collection, resulting in some families of algorithms, including reference counting and so on. Once a block of memory is no longer used or no longer referenced by any pointers, the garbage collector will automatically free the memory preventing the memory leaks. The lack of garbage collectors in C standard language is considered a disadvantage. Although it is possible to implement an insignificant collector if a programmer can accept some limitations such as:

  1. Call the function CollectMalloc(bytes, ptrCount) despite of calling malloc().
  2. All structures pointing to other structures must have the pointers at the top of structures. This will allow the garbage collector to know which elements of that particular structure are pointers.

E.g.:

             typedef struct Node
 {
 struct Node *next, *prev; // should be present at the top
 int value;
 } Node; 
  • While acquiring memory with CollectMalloc(bytes, ptrCount), the number of the pointers at the top of any structure must be specified in the ptrCount.
  • All fixed root pointers such as head and tail pointers must be registered by calling CollectRoot(&head).
  • A garbage collection function must be explicitly called.

With these limitations, the garbage collector can determine the data structures that are no longer referenced so that they can be freed any time. When CollectMalloc() is called, a garbage collector places an OBJECTheader above each requested block of memory.

The requested block of memory will be placed into the doubly linked list, and the number of the pointers at the top of the block of memory will be remembered. When the function CollectGarbage() is called, all the memory blocks will be marked as unreferenced. All the registered fixed root pointers will be used to find the memory blocks that they reference to. Each of the object will then recursively visit other object that it refers. The each visited object will be marked as referenced. These are commonly known as the “mark” phase of the garbage collector. In the next step, if any unreferenced object in the linked list will be freed. This is called the “sweep” phase of garbage collector.

E.g.:

 #include <stdio.h>
 #include <conio.h>
 #define TREE_NODE 2
 typedef struct TreeNode
 {
 struct treeNode *left, *right   // pointers at top
 int value;
 }treeNode;
 treeNode *top, *node0, *node1, *node2;
 int main()
 {
 node 0 = (treeNode*) CollectMalloc( sizeof (treeNode), TREE_NODE);
 node 1 = (treeNode*) CollectMalloc( sizeof (treeNode), TREE_NODE);
 node 2 = (treeNode*) CollectMalloc( sizeof (treeNode), TREE_NODE);
 CollectRoot (&top); //defines a fixed root node
 top = node0;
 node0 -> left = node2;
 CollectGarbage(); //frees the unreferenced node 1
 top = NULL;
 CollectGarbage(); //frees the node 1 and node 2
 return 0;
 } 

The trivial garbage collector implementation enables a programmer to focus on the algorithm instead worrying about any type of the memory leaks. The garbage collector can be improved by adding some more protection to support multiple threads, and by placing an additional magic value at the end of allocated memory blocks to better detect the heap corruption.

The developers using C language think that the memory management is too important to be left to the computer while the LISP (List Processing) developers think memory management is too important to be left to the user. The main drawbacks of garbage collector that not knowing when an unused memory block actually is freed and if it ever will be. This has further consequences when the memory block is an object whose destructor is called at an unspecified time.


Related Topics

Integer Promotions in C

As we know that some of the data types such as char, short int, Enum takes a smaller number of bytes than compared to int. When an operation is applied...

3 minutes read.

Deadlock Detection Program in C

What is Deadlock? A deadlock is a circumstance where a group in the process is halted because they are each holding onto resources while waiting for other methods to obtain them. Think...

5 minutes read.

Find a subarray with a given sum.

Find a subarray with a given sum. The simple solution is to recognize all subarrays one by one and to check each subarray's sum. The quick solution follows the following program. Algorithm: From...

4 minutes read.

#include in C

In the C programming language, #include is another way of inferring a standard, or a user defines file into the application or program. The preprocessor of the programming standard generally...

4 minutes read.

Results of Comparison Operations in C and C++

In this tutorial, we will explore comparison operators and how the system should compare an incoming value supplied as a context parameter to a given value or range of values. A...

2 minutes read.

Write a program that produces different results in C and C++

In this tutorial, we'll explore several programs that, depending on whether they are developed using C or C++ compilers, will produce varying outputs. There are numerous similar programs, but we will just...

2 minutes read.

Bit Fields in C

The size of a structure in C is specified in bits. The primary goal of it is to use memory efficiently, once we understand that a bit's value must fall...

3 minutes read.

Nested if-else statement in C

If we use an if-else statement within another if statement in a C program, it is called a nested if-else statement in C. It helps to check the condition inside...

3 minutes read.

Find Union and Intersection of Two Arrays in C

Union You can find the union of the two sorted arrays using the join merge method on arr1[] and arr2[]. Use two index variables i and j with initial values i =...

4 minutes read.

Modulus on Negative Numbers in C

In this tutorial, we will explore some examples of modulus on negative number. What is Modulus of Negative number? By omitting the minus sign, one can determine the modulus of a negative...

3 minutes read.

Escape Sequence in C

An escape sequence is a sequence of character that used inside the string literal or character.  All the escape sequence is used with the backslash (\) symbol. The list of an...

1 minute read.

Call Back Function in Embedded C

Callback function are one the most remarkable systems in C. A callback function is any code that is passed as a contention to another code, so this is the last...

3 minutes read.

Array Example in C

An array is a collection of similar types of data elements arranged in such a way that any number of values can be assigned to it. It can store values that...

4 minutes read.

Null character in C

Introduction The Null character in the C programming language is used to terminate the character strings. In other words, the Null character is used to represent the end of the string...

3 minutes read.

memcpy() in C

Introduction: Here we discuss about the memcpy() function in C. The memcpy() function is also called the Copy Memory Block function. Used to create a copy of a specific drawing...

4 minutes read.

Variable in C

Variable is an identifier that holds data in memory. It is used to identify input data in a program. The value of the variable can change at the time of...

2 minutes read.

Classification of Programming language

 Classification of Programming language  The programming language represents a set of instructions compiled along with each other to perform a specific task provided by the CPU (Central Processing Unit). A programming...

3 minutes read.

Builtin functions of GCC compiler

Certain built-in functions are present in the GCC compiler. These features are as follows: Function_ built in_popcount (x) The number of 1s in data of the integer type can be counted using...

3 minutes read.

Star Program in C Language

Star Program in C Star patterns are a sequence of * or any other character used to construct any pattern or any like-square geometric form, triangle, hollow square, pyramid, rhombus, etc.  Many programmers worldwide highly...

4 minutes read.

Command line arguments in C

Command line arguments in C The arguments that are generally passed from the line of command are referred to as command line arguments. These command line arguments are always handled by...

3 minutes read.