×

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

Typedef vs define in C

Typedef VS define in C Typedef In the C programming language, a keyword called typedef can be used to give a type a new name. In other words, it is used to...

5 minutes read.

Types of Function in C

A function is a piece of code that accomplish a certain operation for a specific task. There are two types of functions in C: System-defined function (Library Function)User-defined function 1. System defined Function...

8 minutes read.

Why C is a middle level language

The C programming language is generally referred to as a high level language but we glance through the backend of C, i.e the working of C as a programming language...

4 minutes read.

Float in islower() in C

Introduction: This article briefly discusses the float in islower() in C. The islower() function checks if the input character passed inside the function is lowercase. Lowercase letters include (a-z). The islower()...

4 minutes read.

Do WHILE LOOP in C Programming Examples

Before understanding the programming examples of the Do-While loop, we have to know what is Do-While loop in C. So, let's start with the definition of the Do-While loop. What is...

5 minutes read.

Formatted Input and output function in C

Formatted I/O functions display multiple outputs to the user by taking various inputs. All data types like int, float, char and double are supported by the formatted I/O function. In...

4 minutes read.

Prototype in C

A prototype is nothing but a model, a model of initial creation of an intended product. Similarly, in the C programming language, all functions have a prototype. In general, all...

4 minutes read.

Nested loop in C

Definition of Nested Loop A nested loop is generally used when we want to run a loop statement inside another loop statement. This kind of loop is also known as a...

3 minutes read.

Stack implementation in C

Stack implementation in C Stack stores the data in a particular order. It is a linear data structure that follows the principle of the Last In First Out (LIFO) technique where...

3 minutes read.

Heap Sort in C

In this tutorial, we will learn about heap sorting in C language, but before going to Heap sort, we have to know the concept of Complete Binary Tree. What is Complete...

8 minutes read.

Why does sizeof(x++) not Increment x in C

Sizeof() is a much-involved operator in C or C++. It is an incorporated time unary administrator which can be utilized to figure the size of its operand. The consequence of...

5 minutes read.

Loop Questions in C

Question 1: What is For loop syntax? Ans: The syntax that has been used for the ‘for’ loop in C programming language is: for (initialization statement /*for providing a value to variables*/; test...

19 minutes read.

DSA Program in C

How is a Data Structure Implemented? The foundational terms of a data structure are the following terms. Data may be arranged using data structures to make it easier to use. Each data...

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

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.

Multiplication Table in C

Displaying table up to 10 #include <stdio.h> int main() {     int num, i = 1;     printf("     Enter any Number:");     scanf("%d", &num);     printf("Multiplication table of %d: ", num);  ...

1 minute read.

memmove() in C

Introduction: In this article we are discuss about the memmove() function in C. This function transfers memory blocks from one location to another. The memmove() function is declared in the...

3 minutes read.

Use of fflush(stdin) in C

Use of fflush(stdin) in C Usually, fflush() is only used for the output stream. The purpose is to clean (or flush) the output buffer and transfer the buffered data into...

2 minutes read.

Compilation Process in C language

What is the Compilation Process?  The compilation is a method whereby the source code is converted into object code. It is achieved with compiler assistance. The compiler tests the source code for syntactic...

3 minutes read.

C Program for Mean and Median of an Unsorted Array

In this tutorial, we will look at how to determine the mean and median of a given unsorted array. To determine the Mean: To get the average, mean is determined. The formula...

2 minutes read.