Malloc
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;
if (ptr == NULL) {
printf("Memory not allocated.\n");
exit(0);
}
else {
for (i = 0; i < n; ++i) {
ptr[i] = i + 1;
}
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);
if (ptr == NULL) {
printf("Memory not allocated.\n");
exit(0);
}
else {
printf("Memory successfully allocated using calloc.\n");
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);
if (ptr == NULL) {
printf("Memory not allocated.\n");
exit(0);
}
else {
n = 10;
printf("\n\nEnter the new size of the array: %d\n", n);
if (ptr == NULL) {
printf("Reallocation Failed\n");
exit(0);
}
return 0;
}