C - IntroductionC - Hello World ProgramC - Exercise 1C - Basic structure of a C programC - TokensC - Data TypesC - Type ConversionC - Exercise 2C - Character Input Output OperationsC - Input Output operation using scanf and printf functions

Operators

C - Arithmetic OperatorsC - Relational OperatorsC - Logical OperatorsC - Assignment OperatorsC - Increment Decrement OperatorsC - Bitwise Operators

Precedence and Associativity

C - Precedence and AssociativityC - Exercise 3

Conditions

C - If Else decision making statementsC - Switch Case decision making statements

Loop

C - While LoopC - Do While LoopC - For LoopC - Exercise 4

Array

C - ArraysC - Two Dimensional ArraysC - Multi Dimensional ArraysC - Exercise 5

String

C - StringC - Exercise 6C - String Manipulation

Functions

C - FunctionsC - Functions CategoryC - Function Call - Flow of ControlC - RecursionC - Functions and ArraysC - Functions and Strings

Structures

C - StructuresC - Structures and ArraysC - Passing structure to functionC - Function returning structureC - Structure in Structure

Pointers

C - PointersC - Pointers and VariablesC - Pointers and Variables Memory RepresentationC - Pointers Chaining

Pointers and Arrays

C - Pointers and One Dimensional ArrayC - Pointers and Two Dimensional ArrayC - Array of Pointers

Pointers and Strings

C - Pointers and Strings

Pointers and Functions

C - Pointers and Functions - Call by Value and Call by ReferenceC - Function returning pointer

Pointers and Structures

C - Pointers and StructuresC - Pointers and Array of StructuresC - Passing structure pointer to function

Handling Files

C - File Handling - Getting StartedC - File Handling - Read and Write CharactersC - File Handling - Read and Write IntegersC - File Handling - Read and Write multiple dataC - File Handling - Randomly Access Files

Command Line Arguments

C - Command Line Arguments

Dynamic Memory Allocation

C - Dynamic Memory Allocation - Getting StartedC - Dynamic Memory Allocation - malloc functionC - Dynamic Memory Allocation - calloc functionC - Dynamic Memory Allocation - realloc function

C - Dynamic Memory Allocation - malloc function

C Programming

In this tutorial we will learn about malloc function to dynamically allocate memory in C programming language.

The malloc function

We use the malloc function to allocate a block of memory of specified size.

This function returns a pointer of type void so, we can assign it to any type of pointer variables.

The malloc function will return NULL if it fails to allocate the required memory space.

Malloc syntax

Following is the syntax of the malloc function.

ptr = (cast_type *) malloc (byte_size);

Where, ptr is a pointer variable of type cast_type and byte_size is the memory size that we want to allocate.

Malloc example

In the following example we are allocating memory space of size 5 bytes to store 5 characters.

// char pointer
char *cptr;

// allocate memory
cptr = (char *) malloc (5 * sizeof(char));

We can represent this in memory as follows.

We are first computing the byte_size i.e., (5 * sizeof(char)).

Note! sizeof(char) gives us 1 byte and we want to save 5 characters so, total memory space needed is 5x1 = 5 bytes. So, byte_size for this example is 5.

We are passing 5 to the malloc function and on successfully allocating the required memory space it returns a void pointer which we cast into char type pointer by writing (char *).

Then we are assigning the first address of the allocated memory space to a character pointer variable cptr.

Write a program in C to dynamically allocate memory using malloc function to store N integer numbers entered by the user and then print the sum

For this example we will use the malloc function and the byte_size will be (N * sizeof(int)) where, value of N is provided by the user.

We will then convert the pointer to integer type using the casting (int *).

The complete code is given below.

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

int main(void) {
    
  // integer variables
  int N = 0;
  int sum = 0;
  int i;
  
  // integer pointer variables
  int *iptr, *tmp;
  
  // take user input
  printf("Enter value of N [1-10]: ");
  scanf("%d", &N);
  
  // allocate memory
  iptr = (int *) malloc (N * sizeof(int));
  
  // check if memory allocated
  if (iptr == NULL) {
    printf("Unable to allocate memory space. Program terminated.\n");
    return -1;
  }
  
  // take integers
  printf("Enter %d integer number(s)\n", N);
  for (i = 0, tmp = iptr; i < N; i++, tmp++) {
    printf("Enter #%d: ", (i+1));
    scanf("%d", tmp);
    
    // compute the sum
    sum += *tmp;
  }
  
  // display result
  printf("Sum: %d\n", sum);
  
  // free memory location
  free(iptr);

  return 0;
}

Output:

Enter value of N [1-10]: 5 
Enter 5 integer number(s)
Enter #1: 10
Enter #2: 20
Enter #3: 30
Enter #4: 40
Enter #5: 50
Sum: 150

Memory representation of the above code.

We are assuming that an integer value takes 2 bytes of memory. So, in the above image 10 bytes of memory is allocated to save 5 integer variables from location 1000 to 1009.

Pointer variable iptr is at memory location 8000 and it is assigned the first memory location of the allocated space i.e., 1000.

We are using a temporary integer pointer tmp to take user integer number and save it in the allocated memory location.

Note! If we use the iptr pointer variable to take user integer numbers then in the process we will lose the allocated memory location address. So, its better to work with a copy and keep the allocated memory location address safe.

We are using the free() function to free the allocated memory space.

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT