Open In App

Buffer in C Programming

Last Updated : 08 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C, the buffer is referred to as a sequential section of memory that is used to temporarily store some data that is being transferred from one place to another. For Example, in C language, the data entered using the keyboard is first stored in the input buffer, and then it is stored in the memory.

In this article, we will discuss what is a buffer memory, its uses, and limitations in C.

Need of Buffer Memory in C

The need for buffer memory is very case-specific. Take the above example for user input in the C console application. Assume that you have to store a multi-digit number in a variable so you will have to enter them digit by digit. If there is no buffer memory, the first digit you enter will directly be stored inside the variable and you won’t be able to store the rest of the digits.

So basically,

Buffer Memory is required to synchronize the data tranfer by temporarily storing it till it is ready to be transferred or processed.

Moreover, they reduce the I/O calls for read and write operations.

Types of Buffers in C

There are three different types of buffers present in C language used for different purposes:

  1. Hardware Buffer
  2. Cache Buffer
  3. Helper Buffer

The buffers are divided into the above categories based on the purpose they are being used for.

1. Hardware Buffer

Hardware buffer is generally used due to the hardware requirements. They are essential in transferring the data from the memory to the hardware device or vice versa. One such example is the the input operation in C that is discussed above.

Example

The below example demonstrates the use of default input buffer to take input from the user.

C




// C program to take input from the user.
#include <stdio.h>
  
int main()
{
  
    int var;
    printf("Enter the number: ");
    scanf("%d", &var);
    printf("Entered Number: %d", var);
    
    return 0;
}


Output

Enter the number: 2145
Entered Number: 2145

If the buffer was not involved here, only 2 would have been stored inside var.

2. Cache Buffer

These types of buffers are used to optimize the performance of input and output operations by reducing the number of read and write system calls to the OS. Take the example of reading some data from a file in C. We can use fgetc() or fgets() functions to read but if we use fgetc(), we will read the data character by character making as much read() system call as the system as there are characters in the file. But with fgets(), we can use a buffer and read a big amount of data in a single read() system call.

Example

C




// C program to read data from a file using buffer
#include <stdio.h>
#define MAX_DATA_SIZE 1000
  
int pointer = 0;
  
// function to copy buffer to the main storage
void copyData(char* data, char* buffer)
{
    int i = 0;
    while (buffer[i]) {
        if (MAX_DATA_SIZE < pointer) {
            data[pointer++] = buffer[i];
        }
        else {
            return;
        }
    }
}
  
// driver code
int main()
{
    // opening file
    FILE* fptr = fopen("file.txt", "r");
    // creating buffer and data storage array.
    char data[MAX_DATA_SIZE] = "";
    char buffer[100];
  
    // reading data
    while (fgets(buffer, sizeof(buffer), fptr)) {
        copyData(data, buffer);
    }
  
    return 0;
}


The above program will be able to read the 1000 bytes of data in 10 read() system calls.

3. Helper Buffer

Helper buffer are simply those buffers that are used in our program to simplify the algorithm. Such as in converting string to int, we can use the sscanf() to read the string as a buffer and store the data in the integer variable.

Example

C




// C program to illustrate the use of helper buffer in
// string to int conversion
#include <stdio.h>
  
int main()
{
  
    char num[10] = "1234";
    int n;
  
    // counverting num to n
    sscanf(num, "%d", &n);
  
    printf("The number is: %d", n);
  
    return 0;
}


Output

The number is: 1234

Buffer Overflow in C

Buffers in C are crucial for optimizing the flow of data between different components, contribute to overall system performance, and are essential for managing asynchronous communication, load balancing, error handling, and resource utilization. But since it provides the overall management of memory allocation to the users, it also poses potential risks, such as buffer overflow.

In C, Buffer overflow occurs when data exceeds the allocated buffer size, leading to overwriting adjacent memory which can result in serious security issues. Our system may be prompted for malicious action as attacker may exploit this weakness to inject malicious code or manipulating the behaviors of our programs.

C is more prone to buffer exploitation as it is flexible in term of memory management which is directly operated by user and there is no bound checking in most of the functions such as scanf(), gets(), etc.

Example of Buffer Overflow in C

C




// Demonstrating the buffer overflow in C
#include <stdio.h>
  
int main()
{
  
    // declaring two strings one after another in hopes that
    // they get allocated in the adjacent memory
    // location(usually the case)
    char str1[10];
    char str2[25] = "Something meaningful";
  
    // reading strings
    printf("Enter the str1: ");
    scanf("%[^\n]s ", str1);
  
    // printing strings
  printf("str1: %s\nstr2: %s", str1, str2);
    return 0;
}


Output

Enter the str1: this is a sample string
str1: this is a sample string
str2: sample string

As we can see, the data after the 10 characters is stored inside the memory adjacent to the str1 which, in this case is str2. So the previously stored data inside str2 is overwritten.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads