Malloc
Static
Memory allocated during compile time.
Ex:
#include<stdio.h>
int helpme(){
static int y = 0;
y++;
return y;
}
int main(){
int t = 10;
for (int i = 0; i < t; i++)
{
printf("Helped me for %d time\n", helpme());
}
return 0;
}
Register
Memory allocated inside a register.
Ex:
#include <stdio.h>
int main()
{
register int i = 20;
int* a = &i;
printf("%d", *a);
return 0;
}
External Variable
Memory allocated elsewhere and not within the same block where it is used.
Ex:
main.cpp
#include<stdio.h>
extern int n;
int main(){
printf("%d", n);
return 0;
}
Ext.cpp
int n = 12;
Auto
Memory allocated within the block/function they have been declared (which defines their scope).
Ex:
#include<stdio.h>
int main(){
auto t = 10;
for (int i = 1; i <= t; i++)
{
printf("Helped me for %d time\n", i);
}
return 0;
}
Malloc
Used to dinamically allocate a single large block of memory.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int* ptr;
int n, i;
printf("Enter number of elements:");
scanf("%d",&n);
printf("Entered number of elements: %d\n", n);
ptr = (int*)malloc(n * sizeof(int));
if (ptr == NULL) {
printf("Memory not allocated.\n");
exit(0);
}
else {
for (i = 0; i < n; ++i) {
ptr[i] = i + 1;
}
printf("The elements of the array are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
}
return 0;
}
Calloc
Used to dynamically allocate the specified number of blocks of memory of the specified type.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int* ptr;
int n, i;
n = 5;
printf("Enter number of elements: %d\n", n);
ptr = (int*)calloc(n, sizeof(int));
if (ptr == NULL) {
printf("Memory not allocated.\n");
exit(0);
}
else {
printf("Memory successfully allocated using calloc.\n");
for (i = 0; i < n; ++i) {
ptr[i] = i + 1;
}
printf("The elements of the array are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
}
return 0;
}
Realloc
Used to reallocate the given area of memory.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int* ptr;
int n, i;
n = 5;
printf("Enter number of elements: %d\n", n);
ptr = (int*)calloc(n, sizeof(int));
if (ptr == NULL) {
printf("Memory not allocated.\n");
exit(0);
}
else {
printf("Memory successfully allocated using calloc.\n");
for (i = 0; i < n; ++i) {
ptr[i] = i + 1;
}
printf("The elements of the array are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
n = 10;
printf("\n\nEnter the new size of the array: %d\n", n);
ptr = (int*)realloc(ptr, n * sizeof(int));
if (ptr == NULL) {
printf("Reallocation Failed\n");
exit(0);
}
printf("Memory successfully re-allocated using realloc.\
n");
for (i = 5; i < n; ++i) {
ptr[i] = i + 1;
}
printf("The elements of the array are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
free(ptr);
}
return 0;
}
[*]free = used to deallocate the memory to prevent memory leak.