Pointer Assignment 11 — Dynamically Allocate Memory for an Integer Using Pointers
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program: Dynamically Allocate Memory for an Integer Using Pointers — malloc, Use, free

📑 On this page:
  • How Heap Allocation for One Integer Works
  • The Three Steps of Dynamic Allocation
  • Complete C Program
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
📚 In this program, you will learn:
  • How malloc returns a void * that you convert to int *
  • Why you must check for NULL before dereferencing the returned pointer
  • How a heap-allocated integer behaves like any other int — but lives on the heap, not the stack
  • Why free is mandatory and why setting the pointer to NULL afterwards is a good habit
  • The difference between static, automatic (stack), and dynamic (heap) storage duration

How Heap Allocation for One Integer Works

A regular local variable like int x = 42; lives on the stack. Its storage duration is determined by where it's declared: it's created when the enclosing block is entered and destroyed when it's exited. That's fine for most purposes, but sometimes you need memory whose lifetime you control explicitly, or whose size isn't known until runtime. That's what heap allocation is for: malloc asks the C runtime for a block of bytes on the heap, and it returns a pointer to the start of that block — or NULL if the request fails.

For a single integer, the request is simple: malloc(sizeof(int)). The argument is the number of bytes to allocate, so sizeof(int) (usually 4 on modern platforms) is exactly what's needed. malloc's return type is void *, meaning "pointer to an untyped byte sequence." In C, this converts implicitly to int * without a cast — a feature unique to C, and one that keeps the code clean. (In C++, you'd need an explicit cast, but C allows the implicit conversion, and most style guides prefer it.)

The allocated memory is uninitialized. Unlike an array initialization, malloc doesn't set the bytes to zero — the bytes contain whatever was left over from previous use of the heap. So you must write a value to the allocated integer before reading it. That's why the program always writes *p = value; before reading *p back. This is a common source of bugs (using uninitialized memory), and it's worth being explicit about.

💡 In one line: malloc(sizeof(int)) gives you a pointer to one heap-allocated integer, which you must check for NULL, initialize, use, and finally free.

Diagram showing malloc requesting memory from the heap, returning a pointer, writing and reading a value through that pointer, then free releasing the block

The Three Steps of Dynamic Allocation

Step Operation Effect
1. Allocateint *p = malloc(sizeof(int));A block of sizeof(int) bytes on the heap; p points at it
2. Check and useif (p == NULL) { ... } then *p = value;NULL → allocation failed; otherwise *p is a writable integer
3. Releasefree(p); p = NULL;The block is returned to the allocator; the pointer is safely nulled

The three steps are an invariant of good C code: every successful malloc should have a matching free, and between them, no pointer to freed memory should be used. Missing the free leaks memory — the block stays allocated for the rest of the program's life, unavailable to further allocations. Using a pointer after free (use-after-free) is undefined behaviour, and it's one of the most common bugs in production C code. That's why the program sets p = NULL; after freeing — it makes any accidental dereference a clean, defined null-pointer crash rather than silent corruption.

Why allocate a single integer on the heap when a stack variable would do? For one integer, honestly, there's no advantage — a local int x is simpler, faster, and safer. But this assignment is a stepping stone: the same pattern (allocate, check, use, free) scales to arrays, structs, and linked data structures where the heap is truly needed. Mastering it on one integer makes the larger patterns much easier, because the shape of the code is the same — only the size of the allocation changes.

Complete C Program

Program: allocate one integer on the heap, use it, and free it

#include <stdio.h>
#include <stdlib.h>   /* malloc, free */

int main(void) {
    /* 1. Request space for one int on the heap. */
    int *p = malloc(sizeof(int));
    if (p == NULL) {
        fprintf(stderr, "malloc failed: out of memory\n");
        return 1;
    }

    /* 2. Use the allocated memory. */
    *p = 42;
    printf("Value stored at the heap address: %d\n", *p);
    printf("Address returned by malloc:       %p\n", (void *)p);

    /* Modify through the pointer. */
    *p = (*p) * 2;
    printf("After doubling:                   %d\n", *p);

    /* 3. Release the memory and clear the pointer. */
    free(p);
    p = NULL;

    /* This is legal but useless: dereferencing p now would crash cleanly. */
    printf("Memory freed. Pointer has been set to NULL: %p\n", (void *)p);

    return 0;
}
                                    

Program Output

Value stored at the heap address: 42
Address returned by malloc:       0x55f3b4e2a2a0
After doubling:                   84
Memory freed. Pointer has been set to NULL: (nil)
                                

The output shows the three phases: writing 42 through the pointer and reading it back, doubling through the pointer (42 × 2 = 84), and finally freeing the block and nulling the pointer. The address printed by %p is the heap address returned by malloc — it will be different on every run and every platform, because it depends on where the runtime chose to place the allocation. The last line shows (nil) (glibc's way of printing a null pointer), confirming that p is now safe to leave alone.

Step-by-Step Explanation

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

1. The malloc call

malloc(sizeof(int)) requests exactly enough bytes to hold one int — usually 4 on modern systems, but sizeof(int) is the portable way to express it. The return value is void *, which in C converts implicitly to int * without a cast. (Some style guides recommend writing (int *)malloc(...) explicitly for clarity, but modern C practice favors the implicit conversion — it's safer if the type is later changed, because the cast would hide a mismatched-size warning.) If the request succeeds, the returned pointer points at the start of a block of at least sizeof(int) bytes on the heap; the block is not zero-initialized.

2. The NULL check

if (p == NULL) { ... } is essential. malloc returns NULL if the request can't be satisfied — because the program has exhausted its heap, because the request was too large, or because of an internal allocator error. Dereferencing NULL is undefined behaviour, usually a segmentation fault. Checking the return value before using the pointer converts a crash into a graceful error message and exit. For a 4-byte request, failure is unlikely, but the pattern must be there from the start so it becomes habit for larger requests.

3. Writing to the allocated memory

*p = 42; writes the value 42 into the allocated integer. The *p syntax works exactly as it does for a pointer to any other variable — malloc returns a normal pointer, and the memory it points at is a normal int. There's no special "heap pointer" syntax or API: once you have the pointer, the allocated integer behaves just like a stack int, except that its lifetime is controlled by you (via free) rather than by the enclosing block.

4. Reading through the pointer

printf("%d", *p) dereferences the pointer and prints the stored integer. The value 42 is read from the heap and formatted as a decimal integer. This confirms that the write and read are consistent — the pointer really is pointing at writable, readable memory. printf("%p", (void *)p) prints the address as a hexadecimal value; the (void *) cast is required because %p expects void *, and passing a non-void * is technically undefined (though most compilers accept it silently).

5. Modifying through the pointer

*p = (*p) * 2; reads the current value, doubles it, and writes it back. This is the same as x = x * 2; for a stack variable — the pointer indirection doesn't change the arithmetic. It's a good demonstration that heap-allocated memory isn't a second-class citizen: you can read, write, and modify through the pointer exactly as you'd modify a local variable. The only difference is the lifetime.

6. Freeing the memory

free(p) returns the block to the allocator, so it can be reused by future malloc calls. This is not optional — without it, the program leaks the 4-byte block, and if it allocates in a loop, it will eventually exhaust the heap. The block's contents after free are undefined: the allocator may reuse the memory immediately, or leave it in place until needed. That's why using p after free(p) is undefined behaviour — the data p points at may be anything, and there's no way to know.

7. Nulling the pointer after free

p = NULL; is a defensive habit. It doesn't free anything extra — p is just a local variable, and setting it to NULL only changes the variable's value. But it has real value: if the code later accidentally dereferences p, it will crash cleanly (null-pointer dereference) instead of silently using freed memory (use-after-free), which can corrupt other data or produce mysterious wrong results. A null-pointer crash is immediately identifiable; use-after-free bugs can take days to find. Many codebases adopt this as a rule: after free(p), immediately p = NULL;.

8. Why use sizeof(int) instead of a hard-coded 4

Because int is not 4 bytes on every platform — on some embedded systems, or unusual architectures, it may be 2, 4, or 8 bytes. sizeof(int) is a compile-time constant that evaluates to the correct size for the current platform, so malloc(sizeof(int)) works everywhere. Hard-coding 4 would break on platforms where int is a different size. This is the standard C idiom for "allocate one T": malloc(sizeof(T)), or the equivalent malloc(sizeof *p) if p is already declared. The second form is arguably even better because it stays correct if you change the pointer's type.

9. What happens on allocation failure

If malloc returns NULL, the program prints an error to stderr and returns 1 from main. Returning non-zero from main signals failure to the operating system — a script or test harness can check the exit code. The alternative of exit(EXIT_FAILURE) would do the same thing. A common (but risky) alternative is to not check and let the program crash; for a small teaching program, that's sometimes seen, but it's poor practice and the habit is worth forming early.

10. Stack vs heap storage duration

A local int x = 42; has automatic storage duration — it's created when its block is entered and destroyed when the block exits. A malloc'd integer has allocated storage duration — it's created when malloc is called and destroyed when free is called, with no automatic cleanup. This difference matters when you need the value to outlive the function that created it (e.g., returning a pointer to allocated memory from a function that computes something), or when you need to decide at runtime how much memory to allocate (which a stack variable can't do). For a single integer in main, stack allocation would be simpler — but the pattern of heap allocation is the same at every size, so learning it here is worthwhile.

11. Why the cast to void * in printf

printf's %p conversion expects a void *. Passing an int * directly is technically undefined behaviour (the compiler is allowed to assume it matches), even though most implementations happen to work. The cast (void *)p makes the code strictly correct — void * is the C type for "untyped pointer," and it's what %p is designed for. This is a subtle detail that most tutorials skip, but it's worth knowing for production code.

12. Complexity and lifetime

malloc(sizeof(int)) is O(1) amortized — the allocator finds a free block and returns a pointer, possibly doing some bookkeeping but nothing that scales with the size of the request for a 4-byte allocation. free(p) is also O(1). The program does O(1) work total. The memory it allocates lives from malloc until free, which is the programmer's choice — that's the whole point of dynamic allocation. Get the pair right, and memory management becomes a tool; get it wrong, and it becomes a source of leaks, use-after-free bugs, and double-frees.

🎯 Remember this: Dynamic allocation is a three-step pattern — malloc, check/use, free. Always check for NULL, always free what you malloc, and set the pointer to NULL after freeing. Use sizeof rather than hard-coded sizes, and remember that malloc'd memory is uninitialized — you must write before you read.

Frequently Asked Questions

1. Do I need to cast the return value of malloc?

No, and in C, it's usually better not to. malloc returns void *, which converts implicitly to any object pointer type, including int *. Writing int *p = malloc(sizeof(int)) without a cast is idiomatic C. Adding (int *) is harmless in C, but it's required in C++, and it can hide a bug: if you later change p's type to long * but forget to update the cast, the cast will silence the size-mismatch warning that the compiler would otherwise emit. Modern C style guides (like the Linux kernel's) recommend omitting the cast; do whichever matches your codebase's convention, but be aware of the tradeoff.

2. Why does malloc'd memory contain garbage?

Because malloc doesn't initialize the memory it returns — it just hands back a pointer to a block of bytes of the requested size. The bytes contain whatever happened to be there before, which could be leftovers from a previous allocation, OS-level zero pages (for a fresh block from the OS), or arbitrary garbage. Reading uninitialized memory is undefined behaviour. That's why the program writes *p = 42 before reading *p. If you need zero-initialized memory, use calloc(1, sizeof(int)) instead — it zeros the block before returning.

3. What happens if I don't call free?

The memory remains allocated until the program exits. For a single 4-byte allocation in main, this is essentially harmless — the OS reclaims all memory when the process ends. But if you allocate in a loop, or in a long-running program, or in a library function called many times, the accumulated leaks can grow without bound and eventually exhaust the heap. On a system with a memory-limit enforcement, the program will be killed. Leaks are one of the most common bugs in production C code, so the habit of pairing every malloc with a free should be established from the first allocation. Run your code under Valgrind to catch leaks during development.

4. What is the difference between malloc and calloc?

malloc(n) allocates n bytes and returns a pointer to uninitialized memory. calloc(count, size) allocates count * size bytes and zeroes the block before returning. For one integer, malloc(sizeof(int)) and calloc(1, sizeof(int)) request the same amount, but calloc guarantees *p == 0 before you write to it. calloc is slightly slower (it has to zero the block), but it can be safer because an uninitialized read shows up as zero rather than garbage. Most code that needs an initial value writes one explicitly, so malloc is the common choice — but calloc is the right tool when zero-init is what you want.

5. Why set the pointer to NULL after free?

Because free(p) doesn't change p — it changes what p points at (from "valid heap block" to "freed block"), but p still contains the same address value. If the code then accidentally dereferences p, it reads freed memory — use-after-free — which is undefined behaviour. Setting p = NULL after free(p) means a subsequent dereference is a null-pointer dereference, which is also undefined behaviour, but in practice crashes immediately and at a well-defined point. Debugging a null-pointer crash is straightforward; debugging a use-after-free bug (where the freed memory was silently reused by another allocation) can take days. The "free then null" habit is worth forming.

6. What is the time and space complexity?

malloc(sizeof(int)) and free(p) are both O(1) in the common case — the allocator's bookkeeping doesn't depend on the requested size for small allocations. The program does O(1) work total. The "space" complexity is trickier to describe: the program uses sizeof(int) bytes (typically 4) of heap memory for the duration between malloc and free. Unlike a stack allocation, that memory persists across function calls and is released only when free is called, so its lifetime is a programmer decision, not an automatic one.

💡 Tip: Once this works, extend it to allocate an array of integers (assignment #12 — malloc(n * sizeof(int))) and then a string (assignment #13 — malloc(len + 1)). The pattern is identical — request, check, use, free — but each extension raises a new consideration: array length for #12, null-terminator space for #13, and the importance of freeing the right pointer. Working through all three solidifies the malloc/free discipline.

📖 Related Tutorials

  • 12. Dynamically Allocate Memory for an Array Using Pointers
  • 13. Dynamically Allocate Memory for a String Using Pointers
  • 14. Free Dynamically Allocated Memory Using Pointers
  • malloc in C
  • calloc in C
  • All 30 Pointer Assignments

Previous Topic: -->> Pointer Assignments Index   ||   Next Topic: -->> 12. Dynamically Allocate Memory for an Array 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.