Dynamic Memory Allocation
Dynamic Memory Allocation
C prog
Dynamic memory allocation When we declare a variable using a basic data
type, the C compiler automatically allocates
memory space for the variable in a pool of
memory called the stack.
For example, a float variable
takes 4 bytes in stack
#include <stdio.h>
int main() An array with a specified size is allocated in
contiguous blocks of memory ,the size of
{
this array is decide at design time .
float arr[10];
printf("The size of the float array is %d", sizeof(arr));
return 0;
}
when we declare a basic data type or an array,
the memory is automatically managed.
Syntax :
int main()
{
int *ptr;
int main()
{
int *ptr;
int i;
ptr = malloc(sizeof(int)); /* a block of 1 integer */
if (ptr != NULL)
{
*(ptr) = 480; /* assign 480 to 1st integer */
printf("Value of the 1st integer is %d",*(ptr));
}
}
#include <stdlib.h>
int main()
{
int *ptr;
free(ptr);
#include <stdlib.h>
struct node {
int data;
struct node *next;
}; head = n1;
n1->data = 1;
void main() n1->next = n2;
{ n2->data = 2;
n2->next = n3;
struct node *head = NULL; n3->data = 3;
struct node *n1, *n2, *n3; n3->next = NULL; /* <-- indicates end of list */
n1 = (struct node *) malloc(sizeof(struct node));
n2 = (struct node *) malloc(sizeof(struct node)); printf("\nValue of 1st node data = %d",head->data);
n3 = (struct node *) malloc(sizeof(struct node)); printf("\nValue of 1st node data = %d",n1->data);
printf("\nValue of 1st node data = %d",n2->data);
printf("\nValue of 1st node data = %d",n3->data);
}
#include <stdlib.h>
}
#include <stdlib.h>
struct course {
int marks;
char subject[30]; for(i=0;i<noOfRecords;i++)
}; {
printf("Enter subject and marks:\n");
int main() scanf("%s %d", (ptr + i)->subject, &(ptr + i)->marks);
{ }
struct course *ptr;
int noOfRecords,i; printf("Displaying Information:\n");
printf("Enter the number of records: "); for (i = 0; i < noOfRecords; ++i)
scanf("%d",&noOfRecords); {
printf("%s\t%d\n", (ptr + i)->subject, (ptr + i)->marks);
/* Memory allocation for noOfRecords structures*/ }
ptr=(struct course *)malloc(noOfRecords*sizeof(struct course));
free(ptr);
return 0;
}