×

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

Compound Interest Program in C

Interest on loans and deposits is compound interest. This is the most commonly used concept in everyday life. Compound interest on an amount is based on principal and interest earned...

3 minutes read.

2f in C language

Float data type in c: Double-precision floating-point numbers with up to 17 significant digits are stored in the FLOAT data type. FLOAT is equivalent to C's double data type and IEEE...

3 minutes read.

#define in C

#define in C In the C programming language, the preprocessor directive acts an important role within which the #define directive is present that is used to define the constant or the...

3 minutes read.

strcat() Function in C

Strings in c: A string is defined as the set of characters that are enclosed within the double quotations (" "). The String always ends with the null character ("\0"). The...

3 minutes read.

Git Hooks

Git Hooks Overview Just like other version control systems, Git has its way to deliver customized scripts whenever some important activity occurs. The hooks act just like the triggers or catalysts...

4 minutes read.

Multi-dimensional Arrays in C

Multi-dimensional Arrays in C The C programming allows the concept of multi-dimensional arrays. The data within the multidimensional arrays are stored in the tabular form, that is, in a row significant...

3 minutes read.

Union Program in C

 How should a union be defined?  In C programming, a Union is a method used to organize different data types into groups in the same way that Structures are used. We...

4 minutes read.

GPA Calculator in C

GPA stands for Grade Point Average. This GPA is used to measure the student's academic performance in educational institutes. By using this, segregation takes place and lets us know how...

4 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.

Program to Find Mode of an Array in C

Mode is the highest occurring value or number in a given set of data elements. In a group of data values, a value that occurs most frequently is considered to...

3 minutes read.

Distance Vector Routing Protocol Program in c

A distance-vector routing protocol is one of the foremost instructions of routing protocols in pc conversation principle for packet-switched networks. The hyperlink-nation protocol is the alternative foremost class.The Bellman-Ford set...

4 minutes read.

C and C++ Binary Files

What is a binary file? A file in which the content is written in binary format is called a binary file. A binary file is not a text file. There are...

7 minutes read.

Write() function in c

As the name suggests the write () function is used to write the file descriptor. In other words it is used to write any file name without specifying file name,...

3 minutes read.

CRC Program in C

CRC (Cyclic Redundancy Check) is an error-detection algorithm that is used to detect any errors that may have occurred during the transmission or storage of data. The basic idea behind...

4 minutes read.

LCM of two numbers in C

LCM is a mathematical term which stands for Least Common Multiple. LCM of any two numbers is the smallest positive value(number) which is evenly divisible by the two given numbers. Consider...

4 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.

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.

GCD program of two numbers in C

GCD stands for Greatest Common Divisor, which is also known as Highest Common Factor, which can be abbreviated as HCF. Mathematically it can be defined as any two positive integers...

3 minutes read.

Multiplication table program in C using For loop

Before we move on the program of multiplication table of any natural number, first we have to know about the For loop statement. The syntax of ‘for’ loop in C programming...

3 minutes read.

Data Structures And Algorithms in C

C language is one of the most flexible and simple languages. So, it is always better to learn any concept in C language compared to other languages. Let us look...

13 minutes read.