Back to C Programming
2026-07-156 min read

Find Largest Number Using Dynamic Memory Allocation

Learn Find Largest Number Using Dynamic Memory Allocation step by step with clear examples and exercises.

Why This Matters

Dynamic memory allocation is a crucial skill for any C programmer, as it allows the creation of programs that can handle variable amounts of data at runtime. In this lesson, we will delve into using dynamic memory allocation to find the largest number in a list of numbers entered by the user. This problem not only demonstrates the use of dynamic memory allocation but also has practical applications in various areas such as data analysis, finance, and engineering.

Why Dynamic Memory Allocation is Important

Dynamic memory allocation enables C programs to be more flexible and efficient by allowing them to handle variable amounts of data at runtime. This is particularly useful when the size of your data is not known beforehand or when you need to process large datasets.

Prerequisites

To follow this guide, you should have a good understanding of the following C programming topics:

  • Variables and data types
  • Input/Output (I/O) operations using scanf() and printf()
  • Control structures (if...else statements and loops)
  • Pointers and dynamic memory allocation using malloc(), calloc(), and free()

Core Concept

Dynamic memory allocation in C allows you to create memory at runtime, which can be particularly useful when the size of your data is not known beforehand. In this example, we will use dynamic memory allocation to create an array that can store any number of numbers entered by the user.

Here's a step-by-step breakdown of how the program works:

  1. Request the total number of elements from the user using scanf().
  2. Allocate memory for the array using calloc(), which initializes all memory cells to zero.
  3. Read numbers entered by the user and store them in the allocated memory.
  4. Iterate through the array to find the largest number.
  5. Print the largest number found.
  6. Free the dynamically allocated memory using free().
#include <stdio.h>
#include <stdlib.h>

int main() {
int n; // Total number of elements
double *data; // Pointer to the array

printf("Enter the total number of elements: ");
scanf("%d", &n);

// Allocate memory for n elements and initialize them to zero
data = (double *)calloc(n, sizeof(double));
if (data == NULL) {
printf("Error!!! memory not allocated.\n");
return 1;
}

// Read numbers entered by the user
for (int i = 0; i < n; ++i) {
printf("Enter number%d: ", i + 1);
scanf("%lf", data + i);
}

// Find the largest number
double largest = *data;
for (int i = 1; i < n; ++i) {
if (*(data + i) > largest) {
largest = *(data + i);
}
}

// Print the largest number found
printf("Largest number = %.2lf\n", largest);

// Free the dynamically allocated memory
free(data);
return 0;
}

Worked Example

Let's walk through a worked example to better understand how this program works.

  1. Enter the total number of elements: 5
  2. Enter number1: 3.4
  3. Enter number2: 2.4
  4. Enter number3: -5
  5. Enter number4: 24.2
  6. Enter number5: 6.7
  7. Largest number = 24.20

Common Mistakes

Here are some common mistakes to avoid when implementing this program:

  1. Forgetting to include the necessary headers (stdio.h and stdlib.h) at the beginning of your code.
  2. Failing to check if memory allocation was successful, which can lead to a segmentation fault.
  3. Not initializing the largest number before comparing the numbers in the array.
  4. Forgetting to free the dynamically allocated memory after finding the largest number.
  5. Using the wrong data type for the numbers (e.g., using int instead of double).
  6. Not handling invalid input, such as non-numeric input or entering a number larger than the available memory.
  7. Not checking if the user entered a valid number when asking for the total number of elements.
  8. Forgetting to include the necessary libraries (e.g., `) when using functions like calloc() and free()`.
  9. Using malloc() instead of calloc(), which may result in uninitialized memory cells containing random values.
  10. Not properly formatting the output, such as printing the largest number with too many decimal places or forgetting to include a newline character after the output.

Practice Questions

  1. Modify the program to find the smallest number in the list instead of the largest.
  2. Extend the program to handle negative numbers as well.
  3. Implement error handling for invalid input (e.g., non-numeric input or entering a number larger than the available memory).
  4. Modify the program to accept the numbers from a file instead of user input.
  5. Modify the program to find the average of the numbers in the list after finding the largest and smallest numbers.
  6. Implement a function that can dynamically allocate memory for an array, find the largest number, and free the memory. Use this function in the main() function to make the code more modular and easier to maintain.
  7. Modify the program to handle large datasets by using a more efficient data structure like a heap or a binary search tree instead of a simple array.

FAQ

  1. Why do we need dynamic memory allocation if we can use fixed-size arrays? Dynamic memory allocation allows you to handle variable amounts of data at runtime, making your programs more flexible and efficient in situations where the size of the data is not known beforehand or when you need to process large datasets.
  2. What happens if we don't free the dynamically allocated memory? If you don't free the dynamically allocated memory, it will continue to occupy memory even after the program ends, leading to a memory leak. This can cause your program to consume more memory than necessary and potentially lead to performance issues or crashes.
  3. Why do we use calloc() instead of malloc()? calloc() initializes all memory cells to zero, which can be useful when working with arrays. If you use malloc(), the memory cells will contain random values that may cause unexpected behavior in your program.
  4. What should I do if memory allocation fails? If memory allocation fails, you should handle the error and inform the user. In this example, we print an error message and return 1 to indicate that the program has failed. You can also choose to exit the program gracefully or attempt to allocate more memory depending on your specific use case.
  5. Why do we need to include stdlib.h in addition to stdio.h? stdlib.h provides functions for dynamic memory allocation, such as malloc(), calloc(), and free(). Without including it, you won't be able to use these functions in your program.
  6. What is the difference between malloc() and calloc()? Both malloc() and calloc() are used for dynamic memory allocation, but calloc() initializes the allocated memory with zeros, while malloc() does not. This means that using calloc() can be more efficient when working with arrays because you don't have to explicitly initialize each element to zero.
  7. What is the difference between free() and exit()? free() is used to deallocate dynamically allocated memory, while exit() terminates the current program. Using free() allows you to properly manage your program's memory usage, while using exit() abruptly ends the program without giving you a chance to clean up any resources.
  8. Why do we need to include when using free()? The free() function is declared in the stdlib.h header file. Including this header file allows you to use the free() function in your program.
  9. What happens if I forget to include stdlib.h and try to use free()? If you forget to include stdlib.h and try to use free(), the compiler will generate an error because it cannot find the declaration for the free() function. You should always make sure to include the necessary headers when using functions from those libraries.
  10. What is a memory leak, and how can I prevent it? A memory leak occurs when dynamically allocated memory is not properly deallocated, causing it to continue occupying memory even after the program ends. To prevent memory leaks, you should always free any dynamically allocated memory that is no longer needed using the free() function. You can also use tools like Valgrind to help detect and fix memory leaks in your programs.