Back to C Programming
2026-07-156 min read

Example 5: Using sizeof in Dynamic Memory Allocation

Learn Example 5: Using sizeof in Dynamic Memory Allocation step by step with clear examples and exercises.

Why This Matters

In C programming, understanding dynamic memory allocation and the sizeof operator is crucial for creating flexible and efficient applications. By using these tools effectively, developers can manage memory dynamically, avoid common pitfalls such as memory leaks and buffer overflows, and write more robust code. This lesson will help you master dynamic memory allocation and sizeof in C programming.

Prerequisites

Before diving into this lesson, you should have a good understanding of the following topics:

  1. Basic C syntax and programming concepts
  2. Variables and data types in C
  3. Pointers and memory allocation in C
  4. Control structures (if-else, loops)
  5. File I/O (for handling user input and output)
  6. Basic string manipulation functions (e.g., strlen, strcpy, strcmp)

Core Concept

The sizeof operator in C is a unary operator that returns the size of its operand as a value of type size_t. It can be used with variables, arrays, and data types to determine their respective sizes in bytes.

int num = 10;
float pi = 3.14;
char ch = 'A';

printf("Size of int: %zu\n", sizeof(num));
printf("Size of float: %zu\n", sizeof(pi));
printf("Size of char: %zu\n", sizeof(ch));

In this example, we declare three variables of different data types and use the sizeof operator to print their sizes in bytes.

Dynamic Memory Allocation

Dynamic memory allocation can be achieved using functions like malloc(), calloc(), realloc(), and free(). These functions dynamically allocate or deallocate memory at runtime based on our requirements.

int *ptr;
int size = 10;

ptr = (int *) malloc(size * sizeof(int)); // Allocate memory for an array of 10 integers

for (int i = 0; i < size; ++i) {
ptr[i] = i * 2; // Assign values to the allocated memory
}

free(ptr); // Deallocate the memory when no longer needed

In this example, we dynamically allocate an array of 10 integers using malloc(), assign values to it, and then deallocate the memory using free().

Allocating Memory for Arrays

When allocating memory for arrays, it's essential to remember that you should multiply the number of elements by the size of each element. For example:

int arraySize = 10;
int *arr = (int *) malloc(arraySize * sizeof(int));

Initializing Memory with calloc()

The calloc() function initializes dynamically allocated memory to zero. This can be useful when creating arrays of integers or other data types that you want to initialize to specific values.

int *arr = (int *) calloc(arraySize, sizeof(int));

Reallocating Memory with realloc()

The realloc() function changes the size of a dynamically allocated memory block and moves the contents to a new location if necessary. This can be useful when you need to resize an array or other data structure during runtime.

arr = (int *) realloc(arr, newSize * sizeof(int));

Worked Example

Let's consider a simple program that reads a line of text from the user, counts the number of words in the input, and dynamically allocates memory for each word.

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

int main() {
char *input;
int size = 0, words = 0, i = 0;

printf("Enter a line of text: ");
input = (char *) malloc(size + 1); // Allocate memory for an empty string and a null terminator

while ((input[i] = getchar()) != '\n') {
++size;
input = (char *) realloc(input, size + 1); // Reallocate memory to accommodate each character
}

input[i] = '\0'; // Null terminate the string

for (int j = 0; j < i; ++j) {
if (input[j] == ' ') {
++words;
}
}

printf("Number of words: %d\n", ++words); // Account for the first word that doesn't have a space before it

char *tokens = (char *) malloc((words + 1) * sizeof(char)); // Allocate memory for words and null terminator
int tokenIndex = 0;

for (int j = 0; j < i; ++j) {
if (input[j] == ' ') {
tokens[tokenIndex++] = input[j]; // Copy spaces to the token array
} else if (tokenIndex > 0) {
tokens[tokenIndex++] = input[j]; // Copy words to the token array
}
}

tokens[tokenIndex] = '\0'; // Null terminate the token array

for (int j = 0; j <= tokenIndex; ++j) {
printf("Token %d: %s\n", j + 1, tokens + j);
}

free(input); // Deallocate the memory when no longer needed
free(tokens); // Deallocate the memory when no longer needed

return 0;
}

In this example, we dynamically allocate memory to store an input line of text, count the number of words in the input, and then deallocate the memory using free(). We also demonstrate how to split the input into individual words and print them.

Common Mistakes

  1. Forgetting to include necessary headers (stdio.h, stdlib.h, and/or string.h)
  2. Not checking for errors when allocating or reallocating memory
  3. Failing to null terminate the string after dynamically allocating it
  4. Not deallocating memory when no longer needed, leading to memory leaks
  5. Using incorrect data types or sizes in memory allocation functions (e.g., using int instead of size_t)
  6. Forgetting to account for the first word that doesn't have a space before it when counting words
  7. Not properly handling user input, such as ignoring whitespace characters or not accounting for newlines
  8. Failing to copy spaces to the token array when splitting the input into words
  9. Not initializing memory with calloc() if you want all elements to be zero
  10. Using realloc() without checking if the original pointer is non-null before resizing it

Subheadings under Common Mistakes:

  • Checking for Errors in Memory Allocation
  • Handling User Input Correctly
  • Splitting the Input into Words Properly
  • Initializing Memory with calloc()
  • Using realloc() Safely

Practice Questions

  1. Write a program that dynamically allocates an array of 20 integers and initializes them with values from 1 to 20 using calloc().
  2. Modify the worked example to handle input containing multiple lines.
  3. Write a program that reads a line of text, counts the number of vowels, and dynamically allocates memory for each vowel found.
  4. Write a function called myRealloc() that takes a pointer to a dynamically allocated block of memory and a new size, and safely resizes the memory using realloc(). If the original pointer is null, your function should return a new pointer to a newly allocated memory block with the specified size.
  5. Write a program that reads a file line by line, counts the number of words in each line, and dynamically allocates memory for each word found. Print the total number of words across all lines and free the allocated memory when no longer needed.

FAQ

Why should I use dynamic memory allocation instead of fixed-size arrays?

Dynamic memory allocation allows you to create arrays or other data structures with sizes that can change at runtime, making your code more flexible and efficient.

What is the difference between malloc() and calloc()?

Both functions dynamically allocate memory, but calloc() initializes the allocated memory to zero, while malloc() does not.

Why do I need to null terminate a string after dynamically allocating it?

Null terminating a string allows you to treat it as a C-style string and use functions like strlen(), strcpy(), and strcmp().

What happens if I don't deallocate memory when no longer needed?

If you don't deallocate memory, your program will eventually run out of available memory and may crash or behave unpredictably. This is known as a memory leak.

Why should I use realloc() instead of repeatedly calling malloc() and free() to resize an array?

Using realloc() is more efficient because it moves the contents of the original memory block to the new location if possible, avoiding the need to copy data unnecessarily.