- 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
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 buffer | O(n) extra | O(n) |
| Reverse in place | O(1) extra | O(n/2) |
Step-by-Step Approach
- Allocate memory for the string using
malloc(). - Check if
mallocreturnedNULL. If yes, exit. - Read the string from the user with
scanf()orfgets(). - Compute the length with
strlen(). - Use two indices
i = 0andj = length - 1. SwapinputString[i]andinputString[j], then incrementi, decrementj, and repeat untili >= j. - Print the reversed string with
printf(). - 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.