C Program: Dynamic String & Reverse In Place
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program to Dynamically Allocate Memory for a String and Reverse the String In Place

📑 On this page:
  • Purpose & Real-Life Applications
  • What is Reversing In Place?
  • Step-by-Step Approach
  • Complete C Program
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
📚 In this program, you will learn:
  • How to allocate memory for a string at runtime with malloc()
  • How to read a string into a dynamically allocated buffer with scanf()
  • How to use strlen() to find string length
  • How to reverse a string in place using two-pointer swapping
  • How to release memory with free() to avoid leaks

Purpose & Real-Life Applications

Purpose: The motive of this program is to illustrate dynamic memory allocation and string manipulation in C by reversing a string in place — that is, without creating a second copy of the string.

💡 Quick Definition: Reversing in place means rearranging the characters of a string using only the original buffer — no extra array — by swapping characters from both ends moving toward the center.

Real-life applications of string reversal include:

  • Word and text processing applications where string manipulation is required
  • Data encryption algorithms that involve reversed strings
  • Implementation of data structures such as stacks and queues where string reversals may be important
  • Development of palindrome-checking algorithms in which string flipping is a key step
  • Implementation of sorting algorithms that include string reversals as part of the procedure
C program to dynamically allocate memory for a string and reverse the string in place

What is Reversing In Place?

Normally, reversing a string means creating a second buffer and copying characters back to front. That wastes memory — especially for large strings. Reversing in place uses the same buffer and swaps characters at both ends until they meet in the middle.

Approach Memory used Time
Reverse into a new bufferO(n) extraO(n)
Reverse in placeO(1) extraO(n/2)

Step-by-Step Approach

  1. Allocate memory for the string using malloc().
  2. Check if malloc returned NULL. If yes, exit.
  3. Read the string from the user with scanf() or fgets().
  4. Compute the length with strlen().
  5. Use two indices i = 0 and j = length - 1. Swap inputString[i] and inputString[j], then increment i, decrement j, and repeat until i >= j.
  6. Print the reversed string with printf().
  7. Release the memory with free().

Complete C Program

Program: Dynamically allocate memory for a string and reverse it in place

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    char *inputString;
    int i, j, temp;

    /* Dynamically allocate memory for the string */
    inputString = (char *)malloc(100 * sizeof(char));

    if (inputString == NULL)
    {
        printf("\nMemory allocation failed. Exiting program.");
        return 1;
    }

    /* Read input string from the user */
    printf("\nEnter a string: ");
    scanf("%s", inputString);

    /* Reverse the string in place */
    j = strlen(inputString) - 1;
    for (i = 0; i < j; i++, j--)
    {
        temp = inputString[i];
        inputString[i] = inputString[j];
        inputString[j] = temp;
    }

    /* Display the reversed string */
    printf("\nReversed string: %s\n", inputString);

    /* Free dynamically allocated memory */
    free(inputString);
    return 0;
}
                                    

Program Output

Enter a string: Sankalandtech
Reversed string: hcetdnalaknaS
                                

Step-by-Step Explanation

Let's break down this program line by line to understand what's happening:

1. Include header files:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
                                

stdio.h provides printf/scanf. stdlib.h provides malloc/free. string.h provides strlen.

2. Declare pointer and counters:

char *inputString;
int i, j, temp;
                                

inputString will point to the heap-allocated buffer. i and j are the two indices we'll use for swapping. temp holds the character during the swap.

3. Allocate memory for the string:

inputString = (char *)malloc(100 * sizeof(char));
                                

We request space for 100 characters. Using sizeof(char) keeps the code portable (it's 1 on most systems, but the idiom is standard).

4. Check for NULL:

if (inputString == NULL)
{
    printf("\nMemory allocation failed. Exiting program.");
    return 1;
}
                                

Always check the return value of malloc. If it's NULL, using the pointer causes undefined behavior.

5. Read the string:

printf("\nEnter a string: ");
scanf("%s", inputString);
                                

Note: scanf("%s", ...) stops at the first whitespace. For strings containing spaces, use fgets(inputString, 100, stdin) instead.

6. Reverse the string in place:

j = strlen(inputString) - 1;
for (i = 0; i < j; i++, j--)
{
    temp = inputString[i];
    inputString[i] = inputString[j];
    inputString[j] = temp;
}
                                

strlen gives the number of characters. j starts at the last character. Each iteration swaps the characters at i and j, then moves inward. The loop stops when i >= j — that's when we've reached the middle.

7. Print the reversed string and free memory:

printf("\nReversed string: %s\n", inputString);
free(inputString);
                                

free(inputString) releases the heap block. Without it, the memory stays reserved until the process exits — a memory leak.

🎯 Key Takeaway: Reversing in place uses O(1) extra memory and swaps each character exactly once. That's why it's the preferred approach for large strings.

Frequently Asked Questions

1. Why is malloc(100) hardcoded?

It's a demonstration. In real code, you'd either ask the user for the maximum length or read a line with getline() and allocate accordingly.

2. What if the user enters a string longer than 99 characters?

scanf("%s", ...) will overflow the buffer and corrupt adjacent memory. Use scanf("%99s", inputString) or better yet fgets() to limit input length.

3. Can I use this to reverse a string containing spaces?

Not with scanf("%s"). Switch to fgets(inputString, 100, stdin) — then remember to strip the trailing newline.

4. Why do we use strlen instead of sizeof?

sizeof(inputString) returns the pointer size (typically 8 bytes on 64-bit systems), not the string length. strlen(inputString) walks the buffer until the null terminator, which is what we want.

💡 Tip: Compile with gcc -fsanitize=address -g to catch buffer overflows instantly.

📖 Related Tutorials

  • malloc in C
  • calloc in C
  • free in C
  • 1. Dynamic Array of Integers and Sum
  • 3. Dynamic 2D Array and Transpose
  • All DMA Assignments

Previous Topic: -->> 1. Dynamic Array of Integers & Sum   ||   Next topic: -->> 3. Dynamic 2D Array & Transpose


C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • CONDITIONAL STATEMENTS
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • LOOPS STATEMENTS
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processiong
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.