Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Data Structure

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 56

What is heap and stack?

What is heap and stack?

The stack is a place in the computer memory where all the variables that are declared and initialized
before runtime are stored. The heap is the section of computer memory where all the variables created
or initialized at runtime are stored.

What are the memory segments?


The distinction between stack and heap relates to programming. When you look at your computer
memory, it is organized into three segments:
text (code) segment
stack segment
heap segment
The text segment (often called code segment) is where the compiled code of the program itself resides.
When you open some EXE file in Notepad, you can see that it includes a lot of "Gibberish" language,
something that is not readable to human. It is the machine code, the computer representation of the
program instructions. This includes all user defined as well as system functions.

Now let's get to some details.

What is stack?
The two sections other from the code segment in the memory are used for data. The stack is the section
of memory that is allocated for automatic variables within functions.
Data is stored in stack using the Last In First Out (LIFO) method. This means that storage in the
memory is allocated and deallocated at only one end of the memory called the top of the stack. Stack is
a section of memory and its associated registers that is used for temporary storage of information in
which the most recently stored item is the first to be retrieved.
What is heap?
On the other hand, heap is an area of memory used for dynamic memory allocation. Blocks of
memory are allocated and freed in this case in an arbitrary order. The pattern of allocation and size of
blocks is not known until run time. Heap is usually being used by a program for many different
purposes.
The stack is much faster than the heap but also smaller and more expensive.

Heap and stack from programming perspective


Most object-oriented languages have some defined structure, and some come with so-called main()
function. When a program begins running, the system calls the function main() which marks the
entry point of the program. For example every C, C++, or C# program must have one function named
main(). No other function in the program can be called main(). Before we start explaining, let's
take a look at the following example:
int x; /* static stack storage */
void main() {
int y; /* dynamic stack storage */
char str; /* dynamic stack storage */
str = malloc(50); /* allocates 50 bytes of dynamic heap storage */
size = calcSize(10); /* dynamic heap storage */

When a program begins executing in the main() function, all variables declared within main() will be
stored on the stack.
If the main() function calls another function in the program, for example calcSize(), additional
storage will be allocated for the variables in calcSize(). This storage will be allocated in the heap
memory segment.
Notice that the parameters passed by main() to calcSize() are also stored on the stack. If the
calcSize() function calls to any additional functions, more space would be allocated at the heap
again.
When the calcSize() function returns the value, the space for its local variables at heap is then
deallocated and heap clears to be available for other functions.
The memory allocated in the heap area is used and reused during program execution.
It should be noted that memory allocated in heap will contain garbage values left over from previous
usage.
Memory space for objects is always allocated in heap. Objects are placed on the heap.
Built-in datatypes like int, double, float and parameters to methods are allocated on the stack.
Even though objects are held on heap, references to them are also variables and they are placed on
stack.
The stack segment provides more stable storage of data for a program. The memory allocated in
the stack remains in existence for the duration of a program. This is good for global and static
variables. Therefore, global variables and static variables are allocated on the stack.
Why is stack and heap important?
When a program is loaded into memory, it takes some memory management to organize the process. If
memory management was not present in your computer memory, programs would clash with each
other leaving the computer non-functional.

Heap and stack in Java


When you create an object using the new operator, for example myobj = new Object();, it
allocates memory for the myobj object on the heap. The stack memory space is used when you declare
automatic variables.
Note, when you do a string initialization, for example String myString;, it is a reference to an
object so it will be created using new and hence it will be placed on the heap.
.

IT
Programming

Discuss this article or this topic in our discussion forum:


(The table bellow shows a list of 8 most recent topics posted in our discussion forum. Visit our
discussion forum to see more. It is possible the links below are not related to this page, but you can be
certain you will find related posts in the discussion forum. You can post one yourself too.)

Email this article to a friend:


TO:

FROM:
your email here
2+6-3=

Send

How can I link to this web page?


It is easy, just include the code provided below into your HTML code.
<a href="http://www.maxi-pedia.com/what+is+heap+and+stack" title="www.Maxi-Pedia.com: What is
heap and stack?" target="_blank">What is heap and stack?</a>
Bookmark this article with
Delicious Digg StumbleUpon Furl Facebook Google Yahoo
Make sure that you get our latest posts delivered to you by subscribing via your favorite feed reader
.

Introduction to Data Structures


Posted on: April 29, 2010 at 12:00 AM
A data structure is an arrangement of data in a computer's memory or even disk storage. It has a
different way of storing and organizing data in a computer so that it can used efficiently.
Different kind of Data structure is used in different application. For example, B-tree is widely
used in implementation of databases.

Data Structure in C
A memory play a vital role in c because all variable you declare are at first stored in the memory. Some
memory allocation is done at compile time and some at runtime. Memory which is allocated and de-
allocated during the execution of the program is known as dynamic memory. Memory span and shrink
as per application requirement and this is one of major advantage of pointer.
A memory can be categories in following segments
Text Segment
Data Segment
Free Space
Stack Segment
Data Segment in sub-categories in two parts
Static Segment
Heap Segment
The Static Segment hold the global variables and the Heap Segment hold the dynamic variable.
Dynamic memory allocation is done by using malloc() funtion in C.
In this tutorial you will learn about Pointer, Linked List, Stacks, Queues, Trees, and Graphs which are
related with the data structures.
Pointer in C
In the previous tutorial you come to know what is data structure, dynamic memory allocation. Now in
this tutorial you will see the how we declare a pointer variable. How it works with a very simple
example.

Pointer and Structure in C


Structures in C defines the group of contiguous (adjacent) fields, such as records or control blocks. A
structure is a collection of variables grouped together under a single name. It provides an elegant and
powerful way for keeping related data together.

Linear and Non-Linear Data Structure in C


In this tutorial you know the difference between Linear and Non-Linear Data Structure in C.

Array Implementation in C
In this tutorial you will learn how to implement an array in C. There are two function in this given
example one for reading the array element and other for writing on console.
Sum of array element in C
In this tutorial you will know how to get the sum of each element of an array. There are two function in
this given example one for reading the array element and other for writing on console.

Addition of two arrays element in C


In this tutorial you will know how to get the sum of each element of an array. There are three function
in this given example one for reading the array element, second for writing on console and last for
addition of both array's element.

Inverse of an array in C
In this tutorial you will know how to inverse an array in c language. There are three function in this
given example one for reading the array element, second for writing on console and last for inverse of
an array.

Merge of two arrays in C


In this tutorial you will know how to merge two array in c language. There are four function in this
given example one for reading the array element, second for writing on console and third for sorting of
both array and last for merge of two array into one.

Overview of Linked List


In this tutorial you will come to know what is linked list and what are its types.

Singly Linked List


This tutorial demonstrate the implementation of singly linked list.

Doubly Linked List


This tutorial demonstrate how to implement doubly linked list.

Circular Linked List


This tutorial demonstrate how to implement circular linked list.

Count number of nodes


This tutorial demonstrate how to count the number of nodes present in the linked list.

Split a list into two equal size list


This tutorial demonstrate how to splits the list into two equal size list having same data inside.

Merge two list into a single list


This tutorial demonstrate the merging of two link list into one single.

Stack
The stack is one of the most important data structures in computer science. A stack is a last-in first-out
data structure (LIFO).

Push and Pop operation of stack.


This tutorial demonstrate the push and pop operation of stack using array.

Push and Pop operation of stack using linked list.


The fundamental operation of stack is push and pop. The term push is use to place some data element
into the stack and pop is use to remove some data element from the stack.

Queue implementation using array.


This tutorial demonstrate how to insert and delete element in the queue using array.

Queue implementation using linked list.


This tutorial demonstrate how to implement queue using linked list.

Circular queue implementation using array.


This tutorial demonstrate the circular queue implementation using array in c language.

Tree data structure


This tutorial define tree data structure and display how to make a tree.

Representing Graph using adjacency list & perform DFS & BFS
A graph is a collection of nodes and edges.

Pointer in C
Posted on: April 29, 2010 at 12:00 AM
In the previous tutorial you come to know what is data structure, dynamic memory allocation.
Now in this tutorial you will see the how we declare a pointer variable. How it works with a very
simple example.

About Pointer
A pointer is a variable which contain the memory address. It also points to a specific data types. Three
operator are commonly used when dealing with pointer.
1 & address operator
2 * de-referencing operator
3 -> structure pointer operator
Example:
In this example you will see how pointer works.

In the above figure you see that c is a variable of char data-type and it has value "A" inside. The
address of variable c is 0X3000
Now in this figure you see that c is a variable of char data-type and it has value 'A' inside. The address
variable c is 0X3000. And a pointer variable cptr of char data-type. The cptr pointer variable having the
address of c variable rather value. So this is one the important difference between a general variable
and pointer variable is that a pointer variable contains memory address.

A complete example
#include <stdio.h>
void main()
{
char c ='A';
char *cptr;
cptr=&c;
printf("\nThe address of c is\t%p",&c);
printf("\nValue of c is\t\t%c",c);
printf("\n\nThe address of cptr is\t %p",&cptr);
printf("\nValue of cptr is\t%p",cptr);
printf("\nAccess variable which cptr point to is\t%c",*cptr);
}

Output:

From the output of above example you can see that the address of these two variables are different and
the pointer variable holding the address of another variable which it point to.
Download this code
Related Tags for Pointer in C:

Pointer and Structure in C


Posted on: April 29, 2010 at 12:00 AM
Structures in C defines the group of contiguous (adjacent) fields, such as records or control
blocks. A structure is a collection of variables grouped together under a single name. It provides
an elegant and powerful way for keeping related data together.

Description:
In this tutorial you will see how pointer is used with structure. This is a very important example
because all data-structure program work on this principle.
Code:
#include <stdio.h>
#include <conio.h>

struct record
{
char name[20];
int roll;
};
struct record r,*p;

void main()
{
p=&r;
clrscr();
printf("\nEnter the name\n");
scanf("\n%s",&p->name);
printf("\nEnter the roll no\n");
scanf("%d",&p->roll);
printf("\n%s",p->name);
printf("\n%d",p->roll);
}

Code Description:
p=&r assign the address of object to p
*p allow the pointer to access the objects
*p.roll is same as p->roll like used in example.

Output:

Download this code


Related Tags for Pointer and Structure in C:
Previous Index Next

Linear and Non-Linear Data Structure in C


Posted on: April 30, 2010 at 12:00 AM
In this tutorial you know the difference between Linear and Non-Linear Data Structure in C.

Linear Data Structure:


Linear data structure is linear if element is adjacent to each other. It has exactly two
neighbors elements to which it is connected as its previous and next member.

Example of Linear Data Structure


Array
Linked List
Stack
Queue

Non- Linear Data Structure


Non-Linear data structure is that if one element can be connected to more than two
adjacent element then it is known as non-linear data structure.

Example of Linear Data Structure:


Tree
Graph

In the next page you will see a list of program on each above topics.
Related Tags for Linear and Non-Linear Data Structure in C:

In this tutorial you will learn how to implement an array in C. There are two function in this
given example one for reading the array element and other for writing on console.

Array Implementation in C
Code:
#include<stdio.h>
#include<conio.h>
void main()
{
void read(int *,int);
void display(int *,int);
int size[5],i,sum=0;

clrscr();
printf("Enter five elements for an array \n");
read(size,5);
printf("All elements of the array are : \n");
display(size,5);
}

void read(int c[],int i)


{
int j;
for(j=0;j<i;j++)
scanf("%d",&c[j]);
fflush(stdin);
}

void display(int d[],int i)


{
int j;
for(j=0;j<i;j++)
printf("%d ",d[j]);
printf("\n");
}

Output:

Sum of array element in C


Posted on: April 30, 2010 at 12:00 AM
In this tutorial you will know how to get the sum of each element of an array. There are two
function in this given example one for reading the array element and other for writing on console.

Code:
#include<stdio.h>
#include<conio.h>
void main()
{
void read(int *,int);
void display(int *,int);
int a[5],i,sum=0;

clrscr();
printf("Enter five elements for an array \n");
read(a,5);
printf("The list elements are \n");
display(a,5);
for(i=0;i<5;i++)
{
sum+=a[i];
}
printf("The sum of the elements of the array is %d\n",sum);
getch();
}

void read(int c[],int i)


{
int j;
for(j=0;j<i;j++)
scanf("%d",&c[j]);
fflush(stdin);
}

void display(int d[],int i)


{
int j;
for(j=0;j<i;j++)
printf("%d ",d[j]);
printf("\n");
}

Output:

Download this code

Addition of two arrays element in C


Posted on: April 30, 2010 at 12:00 AM
In this tutorial you will know how to get the sum of each element of an array. There are three
function in this given example one for reading the array element, second for writing on console
and last for addition of both array's element.

Code:
#include<stdio.h>
#include<conio.h>
void main()
{
void read(int *,int);
void display(int *,int);
void addarray(int * ,int *,int * ,int);
int a[5],b[5],c[5],i;
clrscr();
printf("Enter the elements for first array \n");
read(a,5);
printf("Enter the elements for second array \n");
read(b,5);
addarray(a,b,c,i);
printf("The sum corresponding element of both array is : \n");
display(c,5);
getch();
}

void addarray(int a[],int b[],int c[],int i)


{
for(i=0;i<5;i++)
{
c[i]=a[i]+b[i];
}
}
void read(int c[],int i)
{
int j;
for(j=0;j<i;j++)
scanf(" %d",&c[j]);
}

void display(int d[],int i)


{
int j;
for(j=0;j<i;j++)
printf(" %d\n",d[j]);
}
Output:

Inverse of an array in C
Posted on: April 30, 2010 at 12:00 AM
In this tutorial you will know how to inverse an array in c language. There are three function in
this given example one for reading the array element, second for writing on console and last for
inverse of an array.

Code:
#include<stdio.h>
#include<conio.h>
void main()
{
void read(int *,int);
void display(int *,int);
void inverse(int *,int);

int a[6],i;
clrscr();
read(a,6);
display(a,6);
inverse(a,6);
display(a,6);
getch();
}

void read(int c[],int i)


{
int j;
printf("Enter six element for an array \n");
for(j=0;j<i;j++)
scanf("%d",&c[j]);
}
void display(int d[],int i)
{
int j;
printf("Element in array are : \n");
for(j=0;j<i;j++)
printf("%d ",d[j]);
printf("\n");
}
void inverse(int x[],int k)
{
int i,temp;
k--;
for(i=0;i<(k/2);i++)
{
temp=x[i];
x[i]=x[k];
x[k]=temp;
k--;
}
}

Output:

Download this code

Merge of two arrays in C


Posted on: May 1, 2010 at 12:00 AM
In this tutorial you will know how to merge two array in c language. There are four function in
this given example one for reading the array element, second for writing on console and third for
sorting of both array and last for merge of two array into one.

Code:
#include<stdio.h>
#include<conio.h>
void main()
{
void read(int *,int);
void display(int *,int);
void sort(int *,int);
void mergelist(int *,int *,int *,int);
int a[5],b[5],c[10];
clrscr();
printf("Enter the elements for the first array \n");
read(a,5);
printf("The elements of first array are : \n");
display(a,5);
printf("Enter the elements for the second array \n");
read(b,5);
printf("The elements of second array are : \n");
display(b,5);
sort(a,5);
printf("The sorted first array in decending order are :\n");
display(a,5);
sort(b,5);
printf("The sorted second array in decending order are :\n");
display(b,5);

mergelist(a,b,c,5);
printf("The elements of merged list is \n");
display(c,10);
getch();
}
void read(int c[],int i)
{
int j;
for(j=0;j<i;j++)
scanf("%d",&c[j]);
}

void display(int d[],int i)


{
int j;
for(j=0;j<i;j++)
printf("%d ",d[j]);
printf("\n");
}
void sort(int arr[] ,int k)
{
int temp;
int i,j;
for(i=0;i<k;i++)
{
for(j=0;j<k-i-1;j++)
{
if(arr[j]<arr[j+1])
{
temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
}

void mergelist(int a[],int b[],int c[],int k)


{
int ptra=0,ptrb=0,ptrc=0;
while(ptra<k && ptrb<k)
{
if(a[ptra] < b[ptrb])
{
c[ptrc]=b[ptrb];
ptrb++;
}
else
{
c[ptrc]=a[ptra];
ptra++;
}
ptrc++;
}
while(ptra<k)
{
c[ptrc]=a[ptra];
ptra++;ptrc++;
}
while(ptrb<k)
{
c[ptrc]=b[ptrb];
ptrb++; ptrc++;

}
}

Output:

Download this code


Related Tags for Merge of two arrays in C:

Overview of Linked List


Posted on: May 1, 2010 at 12:00 AM
In this tutorial you will come to know what is linked list and what are its types.

Linked List
A linked list is a data structure which consists of data record in a sequence such that each data record
have a field of data as well as link reference to its connected node. It do not provide the random access
to any of its member data as it is form of a indexing and the connected node is pre-defined.

There are mainly three kinds of linked lists:


Singly linked list
Doubly linked list
Circular linked list.

Singly link list:


In the singly link list each node have two fields one for data and other is for link reference of the next
node. The node have null only to the last node of the link field. This can be seen in the following
picuture.

Fig: Singly Link List

Doubly link list:


In the doubly link list each node have three field two fields for link which is the reference to next and
previous and one for data record. The node have null only to the first node of previous and last node at
the next. This can be seen in the following picture.

Fig: Doubly Link List

Circular link list:


If talking about singly circular link list each node have two fields one for data record and other for link
reference to the next node. The last node has link reference to the first node. There in no null present in
the link of any node.
Fig: Singly circular link list

In the next page you will see various example with this context.
Related Tags for Overview of Linked List:

Singly Linked List


Posted on: May 1, 2010 at 12:00 AM
This tutorial demonstrate the implementation of singly linked list.

Description:
In this example you will see how to create a node and insert data record in singly link list.

Code:
# include <stdio.h>
# include <stdlib.h>
struct node
{
int data;
struct node *link;
};
struct node *insert(struct node *p , int num)
{
struct node *temp;
if(p==NULL)
{
p=(struct node *)malloc(sizeof(struct node));

if(p==NULL)
{
printf("Error Occurred\n");
exit(0);
}
p-> data = num;
p-> link = NULL;
}
else
{
temp = p;
while (temp-> link != NULL)
temp = temp-> link;
temp-> link = (struct node *)malloc(sizeof(struct node));
if(temp -> link == NULL)
{
printf("Error Occurred\n");
exit(0);
}
temp = temp-> link;
temp-> data = num;
temp-> link = NULL;
}
return
(p);
}
void printlist ( struct node *p )
{
printf("The data values of your list are\n");
while (p!= NULL)
{
printf("%d\t",p-> data);
p = p-> link;
}
}
void main()
{
int n;
int x;
struct node *start = NULL ;
printf("Enter number of nodes you want to create \n");
scanf("%d",&n);
while ( n-- > 0 )
{
printf( "Enter data values for each node\n");
scanf("%d",&x);
start = insert ( start , x );
}
printf("The created single link list is\n");
printlist ( start );
}

Output:

Doubly Linked List


Posted on: May 1, 2010 at 12:00 AM
This tutorial demonstrate how to implement doubly linked list.
Code:
# include <stdio.h>
# include <stdlib.h>
struct dnode
{
int data;
struct dnode *prev, *next;
};

struct dnode *insert(struct dnode *p , struct dnode **q, int n)


{
struct dnode *temp;

if(p==NULL)
{
p=(struct dnode *)malloc(sizeof(struct dnode));
if(p==NULL)
{
printf("Error Occurred\n");
exit(0);
}
p->data = n;
p-> prev = p->next =NULL;
*q =p;
}
else
{
temp = (struct dnode *)malloc(sizeof(struct dnode));

if(temp == NULL)
{
printf("Error Occurred\n");
exit(0);
}
temp->data = n;
temp->prev = (*q);
temp->next = NULL;
(*q)->next = temp;
(*q) = temp;
}
return (p);
}

void printnode( struct dnode *p )


{
printf("All data of created list is\n");
while (p!= NULL)
{
printf("%d\t",p-> data);
p = p->next;
}
}

void main()
{
int n;
int x;
struct dnode *start = NULL ;
struct dnode *end = NULL;
printf("Enter the number of nodes to be created \n");
scanf("%d",&n);
while ( n-- > 0 )
{
printf( "Enter the data values for each node\n");
scanf("%d",&x);
start = insert ( start , &end,x );
}
printnode( start );
}

Output:

Download this code

Circular Linked List


Posted on: May 3, 2010 at 12:00 AM
This tutorial demonstrate how to implement circular linked list.

Description:
In the circular linked list the link of lat node is connected to the first node.

Code:
# include <stdio.h>
# include <stdlib.h>
struct node
{
int data;
struct node *link;
};
struct node *insert(struct node *p , int n)
{
struct node *temp;
if(p==NULL)
{
p=(struct node *)malloc(sizeof(struct node));
if(p==NULL)
{
printf("Error Occurred\n");
exit(0);
}
p-> data = n;
p-> link = p;
}
else
{
temp = p;
while (temp-> link != p)
temp = temp-> link;
temp-> link = (struct node *)malloc(sizeof(struct node));
if(temp -> link == NULL)
{
printf("Error Occurred\n");
exit(0);
}
temp = temp-> link;
temp-> data = n;
temp-> link = p;
}
return (p);
}
void printlist ( struct node *p )
{
struct node *temp;
temp = p;
printf("The data in the list are :\n");
if (p!= NULL)
{ do
{
printf("%d\t",temp-> data);
temp=temp->link;
}while(temp!=p);
}
else
printf("The link is empty \n");
}
void main()
{
int num;
int value;
struct node *start = NULL ;
printf("Enter the number of nodes to be created \n");
scanf("%d",&num);
while ( num-- > 0 )
{
printf( "Enter the data to be placed in a node\n");
scanf("%d",&value);
start = insert ( start , value );
}
printlist ( start );
}

Count number of nodes


Posted on: May 3, 2010 at 12:00 AM

This tutorial demonstrate how to count the number of nodes present in the linked list.

Code:
# include <stdio.h>
# include <stdlib.h>
struct node
{
int data;
struct node *link;
};
struct node *insert(struct node * , int);
int countnode(struct node*);
void printlist (struct node *);

struct node *insert(struct node *p , int n)


{
struct node *temp;
if(p==NULL)
{
p=(struct node *)malloc(sizeof(struct node));
if(p==NULL)
{
printf("Error Occurred\n");
exit(0);
}
p-> data = n;
p-> link = NULL;
}
else
{
temp = p;
while (temp-> link!= NULL)
temp = temp-> link;
temp-> link = (struct node *)malloc(sizeof(struct node));
if(temp -> link == NULL)
{
printf("Error Occurred\n");
exit(0);
}
temp = temp-> link;
temp-> data = n;
temp-> link = NULL;
}
return (p);
}
void printlist ( struct node *p )
{
printf("The data in the list are\n");
while (p!= NULL)
{
printf("%d\t",p-> data);
p = p-> link;
}
}

int countnode (struct node *p )


{
int count=0;
while (p != NULL)
{
count ++;
p = p->link;
}
return(count);
}

void main()
{
int n;
int x;
struct node *start = NULL ;
printf("Enter number of nodes to be created \n");
scanf("%d",&n);
while ( n-- > 0 )
{
printf( "Enter the data for node\n");
scanf("%d",&x);
start = insert ( start ,x);
}
printlist ( start );
n = countnode(start);
printf("\nThe number of nodes in a list are: %d\n",n);
}
Output:

Split a list into two equal size list


Posted on: May 4, 2010 at 12:00 AM

This tutorial demonstrate how to splits the list into two equal size list having same data inside.

Description:
In this example it has mainly three function one for inserting data into list another for printing the list
and last one for split of list.

Code:
# include <stdio.h>
# include <stdlib.h>
struct node
{
int data;
struct node *link;
};

void splitlist(struct node *p, struct node **q, int n)


{
struct node *temp;
int i =1;
temp = p;
while( i < n)
{
temp = temp->link;
i++;
}
*q = temp->link;
temp->link = p;
temp = *q;
while(temp->link != p)
temp = temp ->link;
temp->link = *q;
}

struct node *insertnode(struct node *p , int n)


{
struct node *temp;
if(p==NULL)
{
p=(struct node *)malloc(sizeof(struct node));
if(p==NULL)
{
printf("Error\n");
exit(0);
}
p-> data = n;
p-> link = p;
}
else
{
temp = p;
while (temp-> link != p)
temp = temp-> link;
temp-> link =(struct node *)malloc(sizeof(struct node));
if(temp -> link == NULL)
{
printf("Error\n");
exit(0);
}
temp = temp-> link;
temp-> data = n;
temp-> link = p;
}
return (p);
}
void printlist ( struct node *p )
{
struct node *temp;
temp = p;
printf("The data values in the list are\n");
if(p!= NULL)
do
{
printf("%d\t",temp->data);
temp=temp->link;
} while (temp!= p);

else
printf("empty list\n");
}

void main()
{
int n,num;
int x;
struct node *start1 = NULL ;
struct node *start2=NULL;
printf("Enter the number of node for each splited list \n");
scanf("%d",&n);
num = n;
n*=2; /* this is done to have data multiple of two
so that it split into two equal parts. */
while ( n-- > 0 )
{
printf( "\nEnter data to be placed in node\n");
scanf("%d",&x);
start1 = insertnode ( start1 , x );
}
printlist ( start1 );
splitlist(start1,&start2,num);
printf("\nFirst list is:\n");
printlist(start1);
printf("\nSecond list is:\n");
printlist(start2);

Output:

Download this code


Output:

Download this code


Related Tags for Circular Linked List:
Split a list into two equal size list
Posted on: May 4, 2010 at 12:00 AM
This tutorial demonstrate how to splits the list into two equal size list having same data inside.

Description:
In this example it has mainly three function one for inserting data into list another for printing the list
and last one for split of list.

Code:
# include <stdio.h>
# include <stdlib.h>
struct node
{
int data;
struct node *link;
};

void splitlist(struct node *p, struct node **q, int n)


{
struct node *temp;
int i =1;
temp = p;
while( i < n)
{
temp = temp->link;
i++;
}
*q = temp->link;
temp->link = p;
temp = *q;
while(temp->link != p)
temp = temp ->link;
temp->link = *q;
}

struct node *insertnode(struct node *p , int n)


{
struct node *temp;
if(p==NULL)
{
p=(struct node *)malloc(sizeof(struct node));
if(p==NULL)
{
printf("Error\n");
exit(0);
}
p-> data = n;
p-> link = p;
}
else
{
temp = p;
while (temp-> link != p)
temp = temp-> link;
temp-> link =(struct node *)malloc(sizeof(struct node));
if(temp -> link == NULL)
{
printf("Error\n");
exit(0);
}
temp = temp-> link;
temp-> data = n;
temp-> link = p;
}
return (p);
}
void printlist ( struct node *p )
{
struct node *temp;
temp = p;
printf("The data values in the list are\n");
if(p!= NULL)
do
{
printf("%d\t",temp->data);
temp=temp->link;
} while (temp!= p);

else
printf("empty list\n");
}

void main()
{
int n,num;
int x;
struct node *start1 = NULL ;
struct node *start2=NULL;
printf("Enter the number of node for each splited list \n");
scanf("%d",&n);
num = n;
n*=2; /* this is done to have data multiple of two
so that it split into two equal parts. */
while ( n-- > 0 )
{
printf( "\nEnter data to be placed in node\n");
scanf("%d",&x);
start1 = insertnode ( start1 , x );
}
printlist ( start1 );
splitlist(start1,&start2,num);
printf("\nFirst list is:\n");
printlist(start1);
printf("\nSecond list is:\n");
printlist(start2);

Output:

Download this code

Merge two list into a single list


Posted on: May 6, 2010 at 12:00 AM
This tutorial demonstrate the merging of two link list into one single.
Description:
This example demonstrate how to merge two lists into a single list. Here you find mainly three
function. The insertnode function makes node and insert data into it, printlist function prints all the data
and the mergelist funtion merge the two lists into a single list.

Code:
# include <stdio.h>
# include <stdlib.h>
struct node
{
int data;
struct node *link;
};
struct node *mergelist (struct node *, struct node *);
struct node *insertnode(struct node *p , int n)
{
struct node *temp;
if(p==NULL)
{
p=(struct node *)malloc(sizeof(struct node));
if(p==NULL)
{
printf("Error\n");
exit(0);
}
p-> data = n;
p-> link = NULL;
}
else
{
temp = p;
while (temp-> link!= NULL)
temp = temp-> link;
temp-> link = (struct node *)malloc(sizeof(struct node));
if(temp -> link == NULL)
{
printf("Error\n");
exit(0);
}
temp = temp-> link;
temp-> data = n;
temp-> link = NULL;
}
return (p);
}

void printlist ( struct node *p )


{
printf("The data values in the list are\n");
while (p!= NULL)
{
printf("%d\t",p-> data);
p = p-> link;
}
}

void main()
{
int n;
int x;
struct node *start1 = NULL ;
struct node *start2 = NULL;
struct node *start3 = NULL;
printf("Enter the number of nodes for the first list \n");
scanf("%d",&n);
while ( n-- > 0 )
{
printf( "Enter the data for the first node\n");
scanf("%d",&x);
start1 = insertnode ( start1 ,x);
}

printlist ( start1 );
printf("\nEnter the number of nodes for the second list \n");
scanf("%d",&n);
while ( n-- > 0 )
{
printf( "Enter the data for the second node\n");
scanf("%d",&x);
start2 = insertnode ( start2 ,x);
}
printlist ( start2 );
start3 = mergelist(start1,start2);
printf("\nThe merged list is\n");
printlist ( start3);
}

struct node *mergelist (struct node *p, struct node *q)


{
struct node *r=NULL,*temp;
if (p == NULL)
r = q;
else
if(q == NULL)
r = p;
else
{
if (p->data < q->data )
{
r = p;
temp = p;
p = p->link;
temp->link = NULL;
}
else
{
r = q;
temp =q;
q =q->link;
temp->link = NULL;
}
while((p!= NULL) && (q != NULL))
{
if (p->data < q->data)
{
temp->link =p;
p = p->link;
temp =temp->link;
temp->link =NULL;
}
else
{
temp->link =q;
q = q->link;
temp =temp->link;
temp->link =NULL;
}
}
if (p!= NULL)
temp->link = p;
if (q != NULL)
temp->link = q;
}
return( r) ;
}

Output:

Stack
Posted on: May 7, 2010 at 12:00 AM
The stack is one of the most important data structures in computer science. A stack is a last-in
first-out data structure (LIFO).
Stack Overview
Stack follows the rule of last in first out rule. Mainly two action are performed by stack one is push and
other is pop. The last thing which we placed or push on stack is the first thing we can get when we pop.
A stack is a list of element with insertion and deletion at one end only.
Below depict the operational behaviors of stack. You can see one thing that push and pop operation is
done at one end and whatever element we keep on stack is shown at the top of stack.

Push and Pop operation of stack.


Posted on: June 18, 2010 at 12:00 AM
This tutorial demonstrate the push and pop operation of stack using array.

Description:
In this tutorial of data-structure you will see push and pop operation of stack. In the previous tutorial is
clearly explained the push pop operation. The drawback of implementing stack is that the size of stack
is fixed it cannot grow or shrink.

Code:
#include <stdio.h>
#include <stdlib.h>
void push(int stack[], int *top, int value)
{
if(*top < 4 )
{
*top = *top + 1;
stack[*top] = value;
printf("\nStack element should be less than four\n");
}
else
{
printf("\nThe stack is full can not push a value\n");
exit(0);
}
}
void pop(int stack[], int *top, int * value)
{
if(*top >= 0 )
{
*value = stack[*top];
*top = *top - 1;
}
else
{
printf("\nThe stack is empty can not pop a value\n");
exit(0);
}
}
void main()
{
int stack[4];
int top = 0;
int n,value;
do
{
do
{
printf("\nEnter the element to be pushed\n");
scanf("%d",&value);
push(stack,&top,value);
printf("\nEnter 1 to continue and other key to pop\n");
scanf("%d",&n);
printf("");
} while(n == 1);
printf("\nEnter 1 to pop an element\n");
scanf("%d",&n);
while( n == 1)
{
pop(stack,&top,&value);
printf("\nThe value poped is %d",value);
printf("\nEnter 1 to pop an element\n");
scanf("%d",&n);
}
printf("\nEnter 1 to continue and other key to push\n");
scanf("%d",&n);
} while(n == 1);
}

Output:
Related Tags for Stack:

Push and Pop operation of stack using linked list.


Posted on: June 18, 2010 at 12:00 AM
The fundamental operation of stack is push and pop. The term push is use to place some data
element into the stack and pop is use to remove some data element from the stack.

Description:
In this tutorial of data-structure you will see push and pop operation of stack using linked list. In the
previous tutorial the stack operation in done using array.

Code:
# include <stdio.h>
# include <stdlib.h>
struct node
{
int data;
struct node *link;
};
struct node *push(struct node *p , int value)
{
struct node *temp;
temp=(struct node *)malloc(sizeof(struct node));
if(temp==NULL)
{
printf("No Memory available\n");
exit(0);
}
temp->data = value;
temp->link = p;
p = temp;
return(p);
}

struct node *pop(struct node *p , int *value)


{
struct node *temp;
if(p==NULL)
{
printf(" The stack is empty and cannot pop element\n");
exit(0);
}
*value = p->data;
temp = p;
p = p->link;
free(temp);
return(p);
}

void main()
{
struct node *top = NULL;
int n,value;
do
{
do
{
printf("Enter the element to be pushed in stack\n");
scanf("%d",&value);
top = push(top,value);
printf("Enter 1 to continue\n");
scanf("%d",&n);
} while(n == 1);

printf("Enter 1 to pop an element from stack\n");


scanf("%d",&n);
while( n == 1)
{
top = pop(top,&value);
printf("The value poped is %d\n",value);
printf("Enter 1 to pop an element and other to push\n");
scanf("%d",&n);
}
printf("Enter 1 to continue\n");
scanf("%d",&n);
} while(n == 1);
}

Output:

Push and Pop operation of stack.


Posted on: June 18, 2010 at 12:00 AM
This tutorial demonstrate the push and pop operation of stack using array.

Description:
In this tutorial of data-structure you will see push and pop operation of stack. In the previous tutorial is
clearly explained the push pop operation. The drawback of implementing stack is that the size of stack
is fixed it cannot grow or shrink.

Code:
#include <stdio.h>
#include <stdlib.h>
void push(int stack[], int *top, int value)
{
if(*top < 4 )
{
*top = *top + 1;
stack[*top] = value;
printf("\nStack element should be less than four\n");
}
else
{
printf("\nThe stack is full can not push a value\n");
exit(0);
}
}
void pop(int stack[], int *top, int * value)
{
if(*top >= 0 )
{
*value = stack[*top];
*top = *top - 1;
}
else
{
printf("\nThe stack is empty can not pop a value\n");
exit(0);
}
}
void main()
{
int stack[4];
int top = 0;
int n,value;
do
{
do
{
printf("\nEnter the element to be pushed\n");
scanf("%d",&value);
push(stack,&top,value);
printf("\nEnter 1 to continue and other key to pop\n");
scanf("%d",&n);
printf("");
} while(n == 1);
printf("\nEnter 1 to pop an element\n");
scanf("%d",&n);
while( n == 1)
{
pop(stack,&top,&value);
printf("\nThe value poped is %d",value);
printf("\nEnter 1 to pop an element\n");
scanf("%d",&n);
}
printf("\nEnter 1 to continue and other key to push\n");
scanf("%d",&n);
} while(n == 1);
}
Output:

Queue implementation using array.


Posted on: June 19, 2010 at 12:00 AM
This tutorial demonstrate how to insert and delete element in the queue using array.

Description:
In this tutorial you will see how to implement queue using array and queue insert & delete operations.

Code:
#include <stdio.h>
#define MAX 5
#include <stdlib.h>

void insert(int queue[], int *rear, int value)


{
if(*rear < MAX-1)
{
*rear= *rear +1;
queue[*rear] = value;
}
else
{
printf("The queue is full \n");
exit(1);
}
}

void deleteQ(int queue[], int *front, int rear, int *value)


{
if(*front == rear)
{
printf("The queue is empty \n");
exit(1);
}
*front = *front + 1;
*value = queue[*front];
}

void main()
{
int queue[MAX];
int front,rear;
int n,value;
front=rear=(-1);
do
{
do
{
printf("Enter the element to be inserted in queue\n");
scanf("%d",&value);
insert(queue,&rear,value);
printf("Enter 1 to continue\n");
scanf("%d",&n);
} while(n == 1);
printf("Enter 1 to delete an element from queue\n");
scanf("%d",&n);
while( n == 1)
{
deleteQ(queue,&front,rear,&value);
printf("The value deleted is %d\n",value);
printf("Enter 1 to delete an element from queue\n");
scanf("%d",&n);
}
printf("Enter 1 to continue\n");
scanf("%d",&n);
} while(n == 1);
}

Output:
Queue implementation using linked list.
Posted on: June 19, 2010 at 12:00 AM
This tutorial demonstrate how to implement queue using linked list.

Description:
The advantage of using linked list is that there is no size limit. The size of queue grow and shrink as per
insertion and deletion takes place.

Code:
# include <stdio.h>
# include <stdlib.h>
struct node
{
int data;
struct node *link;
};
void insert(struct node **front, struct node **rear , int value)
{
struct node *temp;
temp=(struct node *)malloc(sizeof(struct node));
if(temp==NULL)
{
printf("No Memory available\n");
exit(0);
}
temp->data = value;
temp->link=NULL;
if(*rear == NULL)
{
*rear = temp;
*front = *rear;
}
else
{
(*rear)->link = temp;
*rear = temp;
}
}

void deleteQ(struct node **front, struct node **rear , int *value)


{
struct node *temp;
if((*front == *rear) && (*rear == NULL))
{
printf(" The queue is empty can not delete Error\n");
exit(0);
}
*value = (*front)->data;
temp = *front;
*front = (*front)->link;
if(*rear == temp)
*rear = (*rear)->link;
free(temp);
}

void main()
{
struct node *front=NULL,*rear = NULL;
int n,value;
do
{
do
{
printf("Enter the element to be inserted\n");
scanf("%d",&value);
insert(&front,&rear,value);
printf("Enter 1 to continue\n");
scanf("%d",&n);
} while(n == 1);
printf("Enter 1 to delete an element\n");
scanf("%d",&n);
while( n == 1)
{
deleteQ(&front,&rear,&value);
printf("The value deleted is %d\n",value);
printf("Enter 1 to delete an element\n");
scanf("%d",&n);
}
printf("Enter 1 to continue\n");
scanf("%d",&n);
} while(n == 1);
}

Output

Download this code


Circular queue implementation using array.
Posted on: June 19, 2010 at 12:00 AM
This tutorial demonstrate the circular queue implementation using array in c language.

Code:
#include <stdio.h>
#define MAX 5
#include <stdlib.h>

void insert(int queue[], int *rear, int front, int value)


{
*rear= (*rear +1) % MAX;
if(*rear == front)
{
printf("The queue is full\n");
exit(0);
}
queue[*rear] = value;
}

void deleteQ(int queue[], int *front, int rear, int * value)


{
if(*front == rear)
{
printf("The queue is empty\n");
exit(0);
}
*front = (*front + 1) % MAX;
*value = queue[*front];
}

void main()
{
int queue[MAX];
int front,rear;
int n,value;
front=0; rear=0;
do
{

do
{
printf("Enter the element to be inserted\n");
scanf("%d",&value);
insert(queue,&rear,front,value);
printf("Enter 1 to continue\n");
scanf("%d",&n);
} while(n == 1);

printf("Enter 1 to delete an element\n");


scanf("%d",&n);
while( n == 1)
{
deleteQ(queue,&front,rear,&value);
printf("The value deleted is %d\n",value);
printf("Enter 1 to delete an element\n");
scanf("%d",&n);
}
printf("Enter 1 to continue\n");
scanf("%d",&n);
} while(n == 1);
}

Output:

Tree data structure


Posted on: June 19, 2010 at 12:00 AM
This tutorial define tree data structure and display how to make a tree.

Description:
A tree data structure that are based on hierarchical tree structure with sets of nodes. A tree is a acyclic
connected graph with zero or more children nodes and at most one parent nodes.

Code:
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *lchild, *rchild;
};

struct node *insertN(struct node *p,int val)


{
struct node *temp1,*temp2;
if(p == NULL)
{
p = (struct node *) malloc(sizeof(struct node));
if(p == NULL)
{
printf("Cannot allocate memory\n");
exit(0);
}
p->data = val;
p->lchild=p->rchild=NULL;
}
else
{
temp1 = p;

while(temp1 != NULL)
{
temp2 = temp1;
if( temp1 ->data > val)
temp1 = temp1->lchild;
else
temp1 = temp1->rchild;
}
if( temp2->data > val)
{
temp2->lchild = (struct node*)malloc(sizeof(struct node));
temp2 = temp2->lchild;
if(temp2 == NULL)
{
printf("Cannot allocate memory\n");
exit(0);
}
temp2->data = val;
temp2->lchild=temp2->rchild = NULL;
}
else
{
temp2->rchild = (struct node*)malloc(sizeof(struct node));
temp2 = temp2->rchild;
if(temp2 == NULL)
{
printf("Cannot allocate memory\n");
exit(0);
}
temp2->data = val;
temp2->lchild=temp2->rchild = NULL;
}
}
return(p);
}

void display(struct node *p)


{
if(p != NULL)
{
display(p->lchild);
printf("%d\t",p->data);
display(p->rchild);
}
}
void main()
{
struct node *root = NULL;
int n,x;
printf("Enter the number of nodes for tree\n");
scanf("%d",&n);
while( n -- > 0)
{
printf("Enter the data value\n");
scanf("%d",&x);
root = insertN(root,x);
}
display(root);
}

Output:

Download this code


Related Tags for Tree data structure:
Previous Index Next

Representing Graph using adjacency list & perform DFS & BFS
Posted on: June 21, 2010 at 12:00 AM
A graph is a collection of nodes and edges.

Description:
This tutorial demonstrate how to create a graph using adjacency list and perform DFS and BFS.
Different kind of graph are listed below:

Directed Graph: A directed graph is one in which edges connect nodes in only one
direction(unidirectional).

Undirected Graph: An undirected graph is one in which edges connect nodes bidirectionally (in both
directions). Node: A node, usually drawn as a circle, represents an item that can be related to other
items or nodes. Nodes are sometimes referred to as vertices.
Edge: An edge represents a connection between nodes. Edges can be either directed or undirected,
depending on the type of graph. Edges can also have weights, which may corresponds distance between
edges.

Connected: A graph is said to be connected if from any node you can reach any other node.

Disconnected: A graph is said to be disconnected if certain groups of nodes from an island that has no
connection to the rest of the graph.

Code:
#include<stdio.h>
#include<conio.h>
#include<alloc.h>

#define max 10

struct node
{
int vertex;
struct node *next;
};
typedef struct node* nodeptr;
typedef struct queue
{
int front,rear;
int arr[max];
};
typedef struct stack
{
int top;
int arr[max];
};
nodeptr getnode()
{
nodeptr p;
p=(nodeptr)malloc(sizeof(struct node));
p->next=NULL;
return p;
}

int empty(struct stack *s)


{
if(s->top==-1)
{
return 1;
}
else
return 0;
}
void push(struct stack *s,int x)
{
if(s->top==max-1)
printf("\n Queue Overflow");
else
{
s->top++;
s->arr[s->top]=x;
}
}
int pop(struct stack *s)
{
int x;
if(empty(s))
printf("\n Queue Overflow..!");
else
{
x=s->arr[s->top];
s->top--;
}
return x;
}

int qempty(struct queue *q)


{
if(q->front > q->rear)
return 1;
else
return 0;
}
void insertq(struct queue *q,int x)
{
if(q->rear==max-1)
printf("\n Queue Overflow..1");
else
{
q->rear++;
q->arr[q->rear]=x;
}
}
int removeq(struct queue *q)
{
int x;
if(qempty(q))
printf("\n Queue Overflow..!");
else
{
x=q->arr[q->front];
q->front++;
}
return x;
}

void init(nodeptr head[],int n)


{
int v;
for(v=1;v<=n;v++)
head[v]=NULL;
}
void initialise_visit(int visited[],int n)
{
int i;
for(i=1;i<=n;i++)
visited[i]=0;
}

void create(nodeptr head[])


{
nodeptr adj;
char ch='y';
int i,v1,v2,v,c;
nodeptr new1,p;
printf("\n <0>Directed");
printf("\n <1>UnDirected");
printf("\n Enter Your Choice:\t");
scanf("%d",&c);

do
{
printf("\n Enter The Edge Between Two Vertices:\t");
scanf("%d%d",&v1,&v2);
new1=getnode();
new1->vertex=v2;
p=head[v1];
if(p==NULL)
head[v1]=new1;
else
{
while(p->next!=NULL)
p=p->next;
p->next=new1;
}
if(c==1)
{
new1=getnode();
new1->vertex=v1;
p=head[v2];
if(p==NULL)
head[v2]=new1;
else
{
while(p->next!=NULL)
p=p->next;
p->next=new1;
}
}
printf("\n Do You Want To Add More Edges In Graph(y/n):\t");
ch=getche();
}while(ch=='y'||ch=='Y');
}

void display(nodeptr head[],int n)


{
int v;
nodeptr adj;
printf("\n Adjancency List Is:\n");
for(v=1;v<=n;v++)
{
printf("\n Head[%d]->",v);
adj=head[v];
while(adj!=NULL)
{
printf("%d ",adj->vertex);
adj=adj->next;
}
printf("\n");
}
}

void DFSR(nodeptr head[],int start,int visited[])


{
nodeptr adj;
visited[start]=1;
printf("\t %d",start);
adj=head[start];
while(adj!=NULL)
{
if(visited[adj->vertex]==0)
{
DFSR(head,adj->vertex,visited);
}
adj=adj->next;
}
}

void DFSN(nodeptr head[],int start,int visited[])


{
nodeptr adj;
struct stack s;
int v;
s.top=-1;
push(&s,99);
visited[start]=1;
printf("\n %d",start);
push(&s,start);
do
{
adj=head[start];
while(adj!=NULL)
{
if(visited[adj->vertex]==0)
{
visited[adj->vertex]=1;
printf("\t%d",adj->vertex);
push(&s,adj->vertex);
start=adj->vertex;
break;
}
else
adj=adj->next;
}
if(adj==NULL)
{
start=pop(&s);
}

}while(!empty(&s));

}
void BFS(nodeptr head[],int start,int visited[])
{
nodeptr adj;
struct queue q;
int v;
q.front=0;
q.rear=-1;
visited[start]=1;
printf("\n %d",start);
insertq(&q,start);
while(!qempty(&q))
{
v=removeq(&q);
adj=head[v];
while(adj!=NULL)
{
if(visited[adj->vertex]==0)
{
visited[adj->vertex]=1;
printf("\t %d",adj->vertex);
}
adj=adj->next;
}
}
}
void main()
{
char c='y';
int ch,start,n,visited[10];
nodeptr head[10];
clrscr();
do
{
clrscr();
printf("\n========Graph========");
printf("\n 1. Create");
printf("\n 2. Display Adjancency List");
printf("\n 3. Depth First Search(Rec)");
printf("\n 4. Depth First Search(Non-Rec)");
printf("\n 5. Breadth First Search");
printf("\n 6. Exit");
printf("\n=====================");
printf("\n Enter Your Choice:\t");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("\n Enter The No. of Vertices In Graph:\t");
scanf("%d",&n);
init(head,n);
create(head);
break;

case 2:
display(head,n);
break;

case 3:
printf("\n Enter The Vertex From Which You Want To Start Traversal");
scanf("%d",&start);
initialise_visit(visited,n);
printf("\n Recursive Depth First Search Is\n");
DFSR(head,start,visited);
break;

case 4:
printf("\n Enter The Vertex From Which You Want To Start Traversal");
scanf("%d",&start);
initialise_visit(visited,n);
printf("\n Non-Recursive Depth First Search Is\n");
DFSN(head,start,visited);
break;

case 5:
printf("\n Enter The Vertex From Which You Want To Start Traversal");
scanf("%d",&start);
initialise_visit(visited,n);
BFS(head,start,visited);
break;

case 6:
break;
}
printf("\n Do You Want To Continue(y/n):\t");
c=getche();
}while(c=='Y'||c=='y');
getch();
}

Output:

Download this code


Related Tags for Representing Graph using adjacency list & perform DFS & BFS:

What is heap and stack?


What is heap and stack?
The stack is a place in the computer memory where all the variables that are declared and initialized
before runtime are stored. The heap is the section of computer memory where all the variables created
or initialized at runtime are stored.

What are the memory segments?


The distinction between stack and heap relates to programming. When you look at your computer
memory, it is organized into three segments:
text (code) segment
stack segment
heap segment
The text segment (often called code segment) is where the compiled code of the program itself resides.
When you open some EXE file in Notepad, you can see that it includes a lot of "Gibberish" language,
something that is not readable to human. It is the machine code, the computer representation of the
program instructions. This includes all user defined as well as system functions.

Now let's get to some details.

What is stack?
The two sections other from the code segment in the memory are used for data. The stack is the section
of memory that is allocated for automatic variables within functions.
Data is stored in stack using the Last In First Out (LIFO) method. This means that storage in the
memory is allocated and deallocated at only one end of the memory called the top of the stack. Stack is
a section of memory and its associated registers that is used for temporary storage of information in
which the most recently stored item is the first to be retrieved.

What is heap?
On the other hand, heap is an area of memory used for dynamic memory allocation. Blocks of
memory are allocated and freed in this case in an arbitrary order. The pattern of allocation and size of
blocks is not known until run time. Heap is usually being used by a program for many different
purposes.
The stack is much faster than the heap but also smaller and more expensive.
Heap and stack from programming perspective
Most object-oriented languages have some defined structure, and some come with so-called main()
function. When a program begins running, the system calls the function main() which marks the
entry point of the program. For example every C, C++, or C# program must have one function named
main(). No other function in the program can be called main(). Before we start explaining, let's
take a look at the following example:
int x; /* static stack storage */
void main() {
int y; /* dynamic stack storage */
char str; /* dynamic stack storage */
str = malloc(50); /* allocates 50 bytes of dynamic heap storage */
size = calcSize(10); /* dynamic heap storage */

When a program begins executing in the main() function, all variables declared within main() will be
stored on the stack.
If the main() function calls another function in the program, for example calcSize(), additional
storage will be allocated for the variables in calcSize(). This storage will be allocated in the heap
memory segment.
Notice that the parameters passed by main() to calcSize() are also stored on the stack. If the
calcSize() function calls to any additional functions, more space would be allocated at the heap
again.
When the calcSize() function returns the value, the space for its local variables at heap is then
deallocated and heap clears to be available for other functions.
The memory allocated in the heap area is used and reused during program execution.
It should be noted that memory allocated in heap will contain garbage values left over from previous
usage.
Memory space for objects is always allocated in heap. Objects are placed on the heap.
Built-in datatypes like int, double, float and parameters to methods are allocated on the stack.
Even though objects are held on heap, references to them are also variables and they are placed on
stack.
The stack segment provides more stable storage of data for a program. The memory allocated in
the stack remains in existence for the duration of a program. This is good for global and static
variables. Therefore, global variables and static variables are allocated on the stack.

Why is stack and heap important?


When a program is loaded into memory, it takes some memory management to organize the process. If
memory management was not present in your computer memory, programs would clash with each
other leaving the computer non-functional.

Heap and stack in Java


When you create an object using the new operator, for example myobj = new Object();, it
allocates memory for the myobj object on the heap. The stack memory space is used when you declare
automatic variables.
Note, when you do a string initialization, for example String myString;, it is a reference to an
object so it will be created using new and hence it will be placed on the heap.
.

IT
Programming

Discuss this article or this topic in our discussion forum:


(The table bellow shows a list of 8 most recent topics posted in our discussion forum. Visit our
discussion forum to see more. It is possible the links below are not related to this page, but you can be
certain you will find related posts in the discussion forum. You can post one yourself too.)

Email this article to a friend:


TO:

FROM:
your email here
2+6-3=

Send

How can I link to this web page?


It is easy, just include the code provided below into your HTML code.
<a href="http://www.maxi-pedia.com/what+is+he

You might also like