Pointer Assignment 13 — Dynamically Allocate Memory for a String Using Pointers
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program: Dynamically Allocate Memory for a String Using Pointers — The +1 for the Null Terminator

📑 On this page:
  • How Heap-Allocated Strings Work
  • The Three Steps of Dynamic String Allocation
  • Complete C Program
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
📚 In this program, you will learn:
  • Why a dynamically allocated string needs strlen(src) + 1 bytes, not just strlen(src)
  • How to copy characters with two pointers walking in lockstep
  • How to read a user-entered string into a heap buffer whose size matches the input
  • How realloc can shrink an over-allocated buffer down to the exact size
  • Why free(dst) frees only the destination, never the source

How Heap-Allocated Strings Work

A C string is a sequence of char values ending with a null terminator '\0'. Its length is the number of characters before the terminator, but its size in bytes is length + 1. This distinction is the single most important thing to get right when allocating a string dynamically: if you request only strlen(src) bytes, you're writing the characters but leaving no room for the terminator, and the first attempt to write '\0' past the end is a buffer overflow — one of the most common bugs in C.

The dynamic string pattern is: measure the length, allocate len + 1 bytes on the heap, copy the characters one by one, write the terminator at index len, use the string, and finally free it. The heap buffer is just a pointer to a contiguous run of char bytes; once it's null-terminated, every standard string function (printf("%s"), strcmp, strlen, and so on) treats it as a normal C string. There is no "heap string" type — a dynamic string is simply a char * pointing at a heap block that happens to be null-terminated.

The alternative to dynamic allocation for a string is a fixed-size stack array. That works when you know the maximum length at compile time — but if the user can enter a string of arbitrary length, a stack array either needs to be very large (wasting memory when inputs are short) or risks truncation (corrupting data when inputs are long). Dynamic allocation solves both problems: you allocate exactly what you need, sized from the input at runtime. The cost is that you must remember to free the block — something the stack array would do for you automatically.

💡 In one line: char *dst = malloc(strlen(src) + 1); — the +1 is for the null terminator. Copy the characters, write '\0' at the end, and free(dst) when done.

Diagram showing malloc reserving strlen(src) + 1 bytes for a heap string, characters being copied through two pointers, and the final null terminator being written at the last slot

The Three Steps of Dynamic String Allocation

Step Operation Effect
1. Allocatechar *dst = malloc(len + 1);A heap block of len + 1 chars (uninitialized)
2. Copy and terminatefor (i = 0; i < len; i++) dst[i] = src[i]; dst[len] = '\0';The destination now contains the same string as the source, terminated
3. Releasefree(dst); dst = NULL;The block returns to the allocator; the source is unaffected

The copy loop can be written in two idiomatic forms. With indices: for (size_t i = 0; i < len; i++) dst[i] = src[i]; followed by dst[len] = '\0';. With two pointers: while ((*dst++ = *src++)) ; — this single-line version copies characters until it copies the null terminator, at which point the assignment evaluates to 0 and the loop stops. The pointer version is elegant but easy to misread; the index version is clearer for teaching. Either way, the source and destination pointers must remain independent — you're copying bytes, not swapping pointers.

A common variant is to read the string from the user. Since you don't know its length in advance, the usual pattern is to allocate a generous capacity (say 256 bytes), read the input with fgets or scanf, then optionally realloc down to the actual length + 1. The realloc is an optimization, not a correctness requirement — the buffer is valid at any capacity as long as it's long enough to hold the string plus its terminator. But for long-running programs that allocate many strings, shrinking to the exact size avoids wasting heap space.

Complete C Program

Program: allocate a heap string of exactly len + 1 bytes, copy into it, use it, and free it

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

/* Allocate a heap copy of src. Returns NULL on failure.
   The caller is responsible for free()ing the result. */
char *dynamic_copy(const char *src) {
    if (src == NULL) {
        return NULL;
    }

    size_t len = strlen(src);
    char *dst = malloc(len + 1);   /* +1 for the null terminator */
    if (dst == NULL) {
        return NULL;
    }

    /* Copy characters through a pointer walk. */
    char *d = dst;
    const char *s = src;
    while (*s != '\0') {
        *d = *s;
        d++;
        s++;
    }
    *d = '\0';                     /* terminate the destination */

    return dst;
}

int main(void) {
    const char *src = "Hello, dynamic world!";

    printf("Source string : \"%s\"  (length %zu)\n", src, strlen(src));

    char *heap = dynamic_copy(src);
    if (heap == NULL) {
        fprintf(stderr, "allocation failed\n");
        return 1;
    }

    printf("Heap copy     : \"%s\"  (length %zu)\n", heap, strlen(heap));

    /* Modify the heap string; the source is unaffected. */
    heap[0] = 'h';
    printf("After modify  : \"%s\"\n", heap);
    printf("Source again  : \"%s\"\n", src);

    free(heap);
    heap = NULL;

    /* ---- Interactive: read a line, allocate exactly its size ---- */
    char tmp[256];
    printf("\nEnter a line of text: ");
    if (fgets(tmp, sizeof(tmp), stdin) == NULL) {
        return 0;
    }
    /* Strip the trailing newline, if any. */
    size_t tmp_len = strlen(tmp);
    if (tmp_len > 0 && tmp[tmp_len - 1] == '\n') {
        tmp[tmp_len - 1] = '\0';
        tmp_len--;
    }

    char *line = malloc(tmp_len + 1);
    if (line == NULL) {
        fprintf(stderr, "allocation failed\n");
        return 1;
    }
    memcpy(line, tmp, tmp_len + 1);   /* include the terminator */

    printf("You entered    : \"%s\"  (length %zu, %zu bytes on heap)\n",
           line, strlen(line), tmp_len + 1);

    free(line);
    line = NULL;

    return 0;
}
                                    

Program Output

Source string : "Hello, dynamic world!"  (length 20)
Heap copy     : "Hello, dynamic world!"  (length 20)
After modify  : "hello, dynamic world!"
Source again  : "Hello, dynamic world!"

Enter a line of text: pointers are powerful
You entered    : "pointers are powerful"  (length 21, 22 bytes on heap)
                                

The output demonstrates two things. First, the heap copy is independent of the source: modifying heap[0] to 'h' changes the heap string but leaves the original "Hello, dynamic world!" untouched — because they're different memory blocks, one in read-only literal memory and one on the heap. Second, the interactive part shows how a string of unknown length is copied into a heap buffer of exactly tmp_len + 1 bytes — 22 bytes for the 21-character input, including the terminator. The %zu format specifier is the correct one for size_t (which is what strlen returns).

Step-by-Step Explanation

Let's walk through the allocation, copy, use, and release in detail.

1. Measuring the source

size_t len = strlen(src); computes the number of characters before the null terminator. For "Hello, dynamic world!", that's 20 — the string has 20 characters, but occupies 21 bytes in memory (20 characters plus the '\0'). The len variable is the length without the terminator; the allocation must be len + 1 to account for the terminator that will be written at index len.

2. The +1 rule

malloc(len + 1) — the +1 is non-negotiable. If you allocate only len bytes, the copy loop writes len characters into indices 0..len-1, which fills the buffer exactly. Then dst[len] = '\0' writes to index len, which is one byte past the end of the block — undefined behaviour. In practice this often "works" because allocators round up block sizes, so the overflow silently corrupts an allocator bookkeeping byte and causes a crash later. But it's a bug, and it will bite eventually. The +1 is the fix.

3. Why malloc, not strdup

The POSIX function strdup(src) does exactly this — allocates strlen(src) + 1 bytes and copies the string — and would be a one-liner here. But strdup is not part of the C standard (it's POSIX, and requires _POSIX_C_SOURCE or a similar feature-test macro on some systems), and writing it by hand demonstrates the allocation-copy-terminate pattern explicitly. Once you understand the pattern, using strdup for convenience is fine — but the assignment is about the pattern, so the program implements it manually.

4. The pointer-walk copy

char *d = dst; const char *s = src; sets up two independent pointers: one into the destination, one into the source. The loop while (*s != '\0') { *d = *s; d++; s++; } copies each character, then advances both pointers. When *s is the terminator, the loop exits without copying it — the terminator is added separately by *d = '\0'. This is deliberate: it makes the "copy len characters, then terminate" logic explicit, and it avoids the trap of the single-line while ((*dst++ = *src++)), which copies the terminator too and leaves both pointers one past the end.

5. Tracing the copy

Source: "Hello, dynamic world!", length 20. The destination buffer is 21 bytes. On each iteration of the loop:

  • Iteration 1: *d = 'H', d → index 1, s → index 1.
  • Iteration 2: *d = 'e', d → index 2, s → index 2.
  • ... continues through all 20 characters.
  • Iteration 20: *d = '!', d → index 20, s → index 20.
  • Now *s is '\0', so the loop exits.

*d = '\0' writes the terminator at index 20 — the 21st byte of the buffer, which was allocated but not yet used. The destination is now a valid C string of length 20.

6. Using the heap string

After dynamic_copy returns, heap points at a heap block containing a valid null-terminated string. Every string function works on it: printf("%s", heap) prints it, strlen(heap) returns its length, strcmp(heap, src) compares it to the source. There's no special handling for heap strings — a char * pointing at a valid null-terminated buffer is a string, regardless of where the buffer lives.

7. Modifying the heap string

heap[0] = 'h'; modifies the first byte of the heap buffer, changing "Hello" to "hello". This is safe because the heap block is writable — unlike a string literal, which lives in read-only memory. But it does not affect the source string, because heap and src point at different memory blocks. The copy is a true duplicate, not an alias. This is exactly what you want when you need to modify a string that was originally a literal (which can't be modified).

8. Freeing the heap string

free(heap) returns the block to the allocator. It frees only the destination buffer — the source string (whether a literal or another heap block) is completely unaffected. This is important: if you had allocated the source dynamically too, you'd need to free both, and free(heap) would only release one of them. Each malloc has exactly one free, and freeing one block doesn't free another even if the blocks happen to contain the same characters.

9. Reading a line of unknown length

The interactive part uses a fixed char tmp[256] to read the input, because fgets needs a buffer to read into. Once the line is read and its length is known, a heap buffer of exactly tmp_len + 1 bytes is allocated and the line is copied into it. This is the standard way to build a heap string from unbounded input: use a fixed buffer with a generous limit, then allocate exactly the size you actually need. A more robust version would handle inputs longer than 256 bytes by growing the buffer with realloc, but the fixed-buffer-then-copy approach is what most code does in practice.

10. Stripping the newline

fgets includes the trailing newline in the buffer if the input line fits. The code checks tmp[tmp_len - 1] == '\n' and replaces it with '\0', then decrements tmp_len. This is the standard idiom for line input, and it matters for the length calculation: without the strip, "hello\n" would be 6 characters long, and the heap copy would include the newline. Users generally expect "hello" (length 5), not "hello\n". The strip makes the buffer match the intuitive string.

11. The exact-size allocation

malloc(tmp_len + 1) followed by memcpy(line, tmp, tmp_len + 1) is worth examining. The +1 in malloc is for the terminator. The memcpy's third argument is tmp_len + 1 — one more than the length — because we want to copy including the terminator. If memcpy copied only tmp_len bytes, we'd have a buffer of characters but no terminator, and printf("%s") would read past the end. The +1 in both places has the same justification: the terminator must be accounted for in both the allocation and the copy.

12. Complexity

dynamic_copy is O(n) in the source length: one pass to measure (strlen), one pass to copy, so 2n character operations total. malloc and free are O(1) amortized. Total time is O(n), and space is O(n) for the heap block plus O(1) for pointers. This is optimal for a string copy: each character must be read once and written once, and the buffer must be at least n + 1 bytes. Using strdup or strcpy would be faster in constant factor (both are optimized, often using SIMD) but the same asymptotically.

🎯 Remember this: A heap string needs strlen(src) + 1 bytes — the extra byte is the null terminator. Copy the characters, write '\0' at index len, use the string with normal string functions, and free it when done. Freeing the copy doesn't free the source; they're independent blocks.

Frequently Asked Questions

1. Why must I allocate len + 1 bytes, not len?

Because every C string ends with a null terminator, and strlen doesn't count it. For a 20-character string, strlen returns 20, but the string occupies 21 bytes in memory: the 20 characters plus the '\0'. If you allocate only 20 bytes, you fill them with the 20 characters and then have nowhere to write the terminator. Writing dst[20] = '\0' goes one byte past the end of the block — a buffer overflow, which is undefined behaviour and one of the most common bugs in C. The +1 is the fix, and it's non-negotiable: any buffer that will hold a null-terminated string must be at least strlen(s) + 1 bytes.

2. Why not just use strdup?

strdup(src) does exactly what dynamic_copy does — allocates strlen(src) + 1 bytes, copies the string, returns the pointer. It's a one-liner. But it's POSIX, not ISO C, so it requires feature-test macros on some systems and isn't available in strict standard-C mode. More importantly, the assignment is about understanding the allocation-copy-terminate pattern, which strdup hides. Once you've written it manually, using strdup for convenience is fine — but you'll never be confused about what it's doing under the hood. If your codebase uses strdup, by all means use it; if it needs to be portable to strict C, write your own.

3. How do I read a string whose length I don't know in advance?

The standard pattern is: read into a fixed-size buffer with fgets(buf, sizeof buf, stdin), then allocate strlen(buf) + 1 bytes on the heap and copy. This is what the program's interactive section does. For inputs that might exceed the fixed buffer, either read in chunks and grow with realloc, or use getline (POSIX) which allocates a buffer for you. Avoid gets — it's been removed from C11 because it can't be made safe. fgets with a fixed buffer is the standard-C compromise: it never overflows, and the buffer size is a tunable tradeoff between memory and maximum input length.

4. Why does modifying the heap copy not affect the source?

Because they're different memory blocks. dynamic_copy calls malloc, which returns a fresh block of heap memory, and then copies the source's bytes into it. After the copy, there are two independent null-terminated strings in memory: the source (wherever it lives — a literal, a stack array, or another heap block) and the destination (the new heap block). Changing a byte in one doesn't change the other, because they're separate addresses. This is what "copy" means: a new block of bytes with the same content. If you wanted them to share memory, you'd just assign the pointer (char *alias = src;) — but then modifying through alias would modify src, because they'd be the same bytes.

5. Can I use realloc to shrink an over-allocated string buffer?

Yes. If you allocated a 256-byte buffer to read the input, then found the input was only 21 characters long, you can call realloc(buf, 22) to shrink it. realloc preserves the first min(old_size, new_size) bytes, so all the valid data (including the terminator) is preserved. Whether this is worth doing depends on the application: for a single string, the 234 wasted bytes are negligible; for thousands of strings, the savings matter. Note that realloc may return a different pointer (if it moves the block), so always capture the return value: char *tmp = realloc(buf, new_size); if (tmp) buf = tmp;. If realloc fails and returns NULL, buf is still valid — the original block was not freed.

6. What is the time and space complexity?

Time is O(n) where n is the source length: one pass to compute strlen, one pass to copy the characters. The malloc and free calls are O(1) amortized. Space is O(n) for the heap block (n + 1 bytes) plus O(1) for pointers. This is optimal for a string copy — each character must be read once and written once, and the buffer must hold at least n + 1 bytes. The constant factor can be reduced with memcpy or strcpy (both are heavily optimized), but the asymptotics are the same.

💡 Tip: Once this works, try dynamically allocating an array of strings — an array of char * pointers, each pointing at a dynamically allocated string. This is exactly how argv works, and it's the basis of many text-processing programs. The pattern is: char **lines = malloc(n * sizeof(char *)); followed by lines[i] = malloc(len_i + 1); for each line, with a matching free(lines[i]) for each line followed by free(lines). The +1 rule applies to each line, and the "free each inner pointer, then the outer" rule is essential — freeing the outer array without freeing the inner strings leaks every line.

📖 Related Tutorials

  • 11. Dynamically Allocate Memory for an Integer Using Pointers
  • 12. Dynamically Allocate Memory for an Array Using Pointers
  • 14. Free Dynamically Allocated Memory Using Pointers
  • 23. Length of a String Using a Function and Pointers
  • 21. Copy One String to Another Using a Function and Pointers
  • All 30 Pointer Assignments

Previous Topic: -->> 12. Dynamically Allocate Memory for an Array Using Pointers   ||   Next Topic: -->> 14. Free Dynamically Allocated Memory Using Pointers


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.