Write a C program for Dynamic Memory Allocation(malloc).

Function Main
Declare N, sum, i as integers
Declare iptr, tmp as integer pointers
Print "Enter value of N [1-10]: "
Read N from user
Allocate memory for iptr with size N * sizeof(int)
If iptr is NULL
    Print "Unable to allocate memory space. Program terminated."
    Return -1
Print "Enter N integer number(s)"
For i from 0 to N-1
    Print "Enter #(i+1): "
    Read input and store it in tmp
   Add the value of tmp to sum
Print "Sum: ", sum
Free the memory allocated for iptr
End

#include <stdio.h>


int main(void) {
//!ShowMemory(start=1000)
    
  // 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;
}

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
     

More Example:

//Example: 02
#include <stdlib.h>
int main() {
    //! showMemory(start=1000)
    int * p = malloc(4 * sizeof(int));
    int * q = malloc(1 * sizeof(int));
    free(q);
    int * r = malloc(2 * sizeof(int));
    return 0;
}
//Run this code in C Programming Manual Tracing

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.