Dynamic Memory Allocation in C

Photo by Liam Briese on Unsplash
  1. Stack: A stack is a area of computer’s memory which stores variables created by a function. In stack, variables are declared, stored and initialized during runtime and destroyed after program execution.
  2. Heap: The heap is used by programming languages to store global variables. It supports Dynamic memory allocation. Heap does not destroy data itself.

Dynamic Memory Allocation(DMA)

Memory allocation: malloc()

Syntax

Example

int *x;
x = (int*)malloc(150 * sizeof(int));

Contiguous allocation: calloc()

Syntax

void *calloc(items, size);

Example

int *x;
x = (float*) calloc(150, sizeof(float));

Re-allocation: realloc()

Syntax

void* realloc(pointer, new-size)

Example

int *x;
x = (int*)malloc(150 * sizeof(int));
x = (int*)realloc(x,300);

Free allocation: free()

Syntax

free(ptr);

Example

int *x;
x = (int*)malloc(150 * sizeof(int));
free(x);

Dynamic Memory Allocation Example

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

void main()
{
int i, n;
int *x;

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

x = (int*) calloc(n,sizeof(int));

if(x == NULL)
{
printf("Not enough space.");
}

for(i = 0; i < n; i++)
{
scanf("%d", x+i);
}
for(i = 1; i < n; i++)
{
if(*x < *(x+i))
{
*x = *(x+i);
}
}

printf("Greatest number is %d", *x);
free(x);

}

--

--

--

Hola! They call me Hacker

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Why Should You Learn Rust?

The Hardest Part is Just to Start

Introduction to Apache Hadoop

How CSS & HTML Interact

Left rotation of an array using vectors in C++

The tools, they are a-changing

CS371p Fall 2021: Week 2

Tutorial No.2 for Plato Farm’s newcomers

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
crysp

crysp

Hola! They call me Hacker

More from Medium

Application Programming Interface

Linked Lists for Beginners

From Java to C++