EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login

Memory Allocation in C

Home » Software Development » Software Development Tutorials » C Programming Tutorial » Memory Allocation in C

Memory Allocation in C

Introduction to Memory Allocation in C

Memory allocations, in general, mean where computer programs and services are executed to reserve partially or complete space or virtual memory of a computer, this process is known as memory allocation. This process is hardware operation and is achieved by memory management through Operating systems and software applications. In general, there are static and dynamic memory allocations, whereas, in C programming language, we will see about dynamic memory allocation where programs are allocated during run time in memory and static memory allocation is a process of allocating memory while writing the C program which means memory is allocated at compile time.

How does Memory Allocation work in C?

In C language, static and dynamic memory allocation is also known as stack memory and heap memory which are allocated during compile time and run time, respectively.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

1. Static Memory Allocation

As we discussed static memory allocation is the allocation of memory for the data variables when the computer programs start. This type of allocation is applied to only global variables, file scope variables and also to those variables that are declared as static. This type of allocation is having a drawback when you are allocating memory we should know the exact memory before allocating as this process allocates fixed memory and cannot be changed after allocating.

1. There are a few features of static memory allocation. They are: this type of allocation allocates variables permanently; hence the memory in this type of allocation cannot be reused and is, therefore, less efficient. This allocation uses the stack for implementing the allocation process.

Let us see an example below:

Code:

void play
{
int x;
}
int main()
{
int y;
int c[10];
return 1;
}

Explanation: In the above program, the variables x, y, and care statically allocated so the memory is strictly allocated at compile time for the variable data. Note that the deletion of memory is necessary when the variables are not in use because it will lead to memory leakage. Therefore in static memory allocation, it automatically frees the memory based on the scope of the variable which means as soon as the variable’s cope is over the memory gets released.

Popular Course in this category
C Programming Training (3 Courses, 5 Project)3 Online Courses | 5 Hands-on Projects | 34+ Hours | Verifiable Certificate of Completion | Lifetime Access
4.5 (5,617 ratings)
Course Price

View Course

Related Courses
C++ Training (4 Courses, 5 Projects, 4 Quizzes)Java Training (40 Courses, 29 Projects, 4 Quizzes)

2. A variable can internally or externally be declared as static in which its value persists until the end of the program, where this can be done using the keyword static before the variable declaration. There can be internal or external static variables that are declared inside or outside the function.

Let us see an example:

#include<stdio.h>
void stat(void);
int main()
{
int i;
for(i=1; i<=3 ; i++)
stat();
return 1;
}
void stat(void)
{
static int n = 0;
n = n+1;
printf("n = %d""\n", n);
}

Output:

Memory Allocation in C - 1

2. Dynamic Memory Allocation

As discussed above dynamic memory allocation is allocation of memory during runtime or during program execution. Dynamic memory allocation provides different functions in the C programming language. They are: malloc(), calloc(), realloc(), free(). Let us see in detail.

1. malloc()

This method allocates the space in the memory during execution but will not initialize the memory allocation during execution as it carries garbage values and if it cannot allocate requested memory then it returns a null pointer.

Syntax:

(CastType*) malloc(size);

Code:

mptr = (int*) malloc(100 * sizeof (int));

In the above example, the statement allocates 200 bytes of memory because the int size in C is 2 bytes and the variable mptr pointer holds the address of the first byte in the memory.

2. calloc()

This is also known as contiguous allocation. As in malloc() will not initialize any memory bit. But in calloc() it allocates the memory along with initializing the bits to zero.

Syntax:

(CastType*) calloc(n, size)

Code:

cptr = (int*) calloc(35, sizeof (int));

In this function, the above example statement allocates contiguous memory space for about 35 elements of data type “int”.

3. free()

As discussed above the memory space should be freed or released if not in use. In Dynamic memory allocation, malloc() and calloc() function only allocates memory but cannot free the memory on their own so this is done using free() method explicitly to release the memory that is not in use to avoid memory leakage.

Syntax:

free (pointer_variable);

Code:

#include <stdio.h>
#include <stdlib.h>
int main()
{
int *p, *p1;
int x, i;
x = 5;
printf("Enter number of elements to allocate in memory : %d\n", x);
p = (int*)malloc(x * sizeof(int));
p1 = (int*)calloc(x, sizeof(int));
if (p == NULL || p1 == NULL) {
printf("Memory is not allocated.\n");
exit(0);
}
else {
printf("Memory has been successfully allocated using malloc.\n");
free(p);
printf("Malloc Memory has been successfully freed or released.\n");
printf("\nMemory has been successfully allocated using calloc.\n");
free(p1);
printf("Calloc Memory has been successfully freed or released.\n");
}
return 0;
}

Output:

Memory Allocation in C - 2

4. realloc()

As the name suggests, in dynamic memory allocation if suppose a user wants to allocate more memory which means more memory than specified or required by the program then we can use this realloc() function to alter the size of memory that was allocated previously.

Syntax: 

realloc (pointer_variable, n);

Code:

Suppose if we want to change the size of memory from 200 bytes to 600 bytes. Let us how it can be done using realloc().

char *rptr;
rptr = malloc(200);
rptr = realloc(rptr, 600);

Conclusion

Memory allocation in C programming language is simple using static memory allocation which allocates memory during compile time or we can say before the program execution and it also has another type known as dynamic memory allocation which allocates memory during run time or allocating memory during program execution which uses 4 different functions such as malloc(), calloc(), free() and realloc(). There are different pros and cons of both methods.

Recommended Articles

This is a guide to Memory Allocation in C. Here we discuss static and dynamic memory allocation in C language with functions. You can also go through our other related articles to learn more –

  1. Multidimensional Array in C
  2. Types of Memory in Java
  3. C Literals
  4. What is Heap Memory?

All in One Software Development Bundle (600+ Courses, 50+ projects)

600+ Online Courses

50+ projects

3000+ Hours

Verifiable Certificates

Lifetime Access

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
C Programming Tutorial
  • Advanced
    • Constructor in C
    • Encapsulation in C
    • C Storage Classes
    • Static Keyword in C
    • File Handling in C
    • Queue in C
    • Hexadecimal in C 
    • typedef in C
    • Memory Allocation in C
    • Linked List in C
    • Volatile in C
    • Tokens in C
    • Expression in C
    • Regular Expression in C
    • Error Handling in C
    • Types of Errors in C
    • Preprocessor in C
    • Preprocessor Directives in C
    • fscanf() in C
    • #Pragma in C
    • #ifndef in C
    • #undef in C
    • Macros in C
  • Basic
    • Introduction to C
    • What is C
    • Career in C Programming
    • Advantages of C
    • How to Install C
    • Best C Compilers
    • Data Types in C
    • Variables in C
    • C Keywords
    • C Command
    • Command Line Arguments in C
    • C Literals
    • Constants in C
    • Unsigned Int in C
    • String in C
  • Pointers
    • Pointers in C
    • Null pointer in C
    • Function Pointer in C
    • Double Pointer in C
    • Void Pointer in C
    • Const Pointer in C
    • Dangling Pointers in C
    • Pointer Arithmetic in C
  • Operators
    • C Operators
    • Arithmetic Operators in C
    • Relational Operators in C
    • Assignment Operators in C
    • Logical Operators in C
    • Conditional Operator in C
    • Modulus Operator in C
    • Ternary Operator in C
    • Address Operator in C
    • Unary Operator in C
    • Operators Precedence in C
    • Left Shift Operator in C
  • Control Statement
    • Control Statements in C
    • If Statement in C
    • If-else Statement in C
    • Else if Statement in C
    • Nested if Statement in C
    • #else in C
    • Structure Padding in C
    • Nested Structure in C
    • Continue Statement in C
    • Break Statement in C
    • Switch Statement in C
    • Goto Statement in C
  • Loops
    • Loops in C
    • For Loop in C
    • While Loop in C
    • Do While Loop in C
    • Nested Loop in C
    • Infinite Loop in C 
  • Function
    • Math Functions in C
    • Hashing Function in C
    • Recursive Function in C
    • Power Function in C
    • fputs in C
    • C puts() Function
    • fprintf() in C
    • fseek() in C
    • Stderr in C
    • ASCII Value in C
    • strcat() in C
    • Inline Function in C
    • sizeof() in C
    • Function Prototype in C
    • C ftell()
  • Array
    • Arrays in C Programming
    • 2-D Arrays in C
    • 3D Arrays in C
    • Multidimensional Array in C
    • Array Functions in C
    • Strings Array in C
  • Sorting
    • Sorting in C
    • Heap Sort in C
  • C programs
    • Patterns in C Programming
    • Star Patterns in C
    • Number Patterns in C
    • Swapping in C
    • Reverse Number in C
    • Palindrome in C Program
    • Factorial in C
    • Fibonacci Series in C
    • Square Root in C
    • Random Number Generator in C
    • Prime Numbers in C
    • Escape Sequence in C
    • Reverse String in C
    • Leap Year Program in C
    • Anagram Program in C
    • Strong Number in C
    • String Concatenation in C
    • C Programming Matrix Multiplication
    • Decimal to Octal in C
    • Expression Evaluation in C
    • Decimal to Hexadecimal in C
  • Interview question
    • C Programming Interview Questions

Related Courses

C Programming Training Course

C++ Training Course

Java Training Course

Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

© 2020 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you
Book Your One Instructor : One Learner Free Class

Let’s Get Started

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA Login

Forgot Password?

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

Special Offer - C Programming Training Course Learn More