Showing posts with label Memory Allocation. Show all posts
Showing posts with label Memory Allocation. Show all posts

'new operator' throw and nothrow

I used to always think and while coding take care that to check if memory allocation is successful, we need to check if the returned pointer is not NULL. Well, in MSVC8 this may not necessarily be true. Depending on the library you include (see here) you may end up with either a throw or a NULL. The partial good news is that you can in future write your code to not throw memory alloc failure. See example:



//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
#include<iostream>

using namespace
std;

int
main()
{

try

{

char
* p = new char[0x7fffffff];
if
(!p)
{

cout<<"Memory allocation for q failed. NULL returned."<<endl;
}
}

catch
(...)
{

cout<<"Exception caught by ..."<<endl;
}


char
* q = new (std::nothrow) char[0x7fffffff];
if
(!q)
{

cout<<"Memory allocation for q failed. NULL returned."<<endl;
}


return
0;
}




The output is as follows:

Memory Allocation for char*

One common problem that I have noticed is that people copy char* pointers thinking that the pointers will be valid when used but this is rarely the case. See the example below.


//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//Example demonstrates allocation of memory for char*
#include<iostream>

using namespace
std;

typedef struct
{
char
const * name;
}
TypeInfo;

TypeInfo* MakeType(const char *typeName)
{

TypeInfo* newNamedTypeInfo = new TypeInfo;

char
* newTypeName = new char[strlen(typeName) + 1];
strcpy(newTypeName, typeName);
newNamedTypeInfo->name = newTypeName;

return
newNamedTypeInfo;
}


int
main()
{

TypeInfo* testType = MakeType("Apple Banana");
cout << "testType->name = " << testType->name << endl;

return
0;
}





Please suggest any improvements.

The output is as follows:
Note that there is a memory leak in the program if you can spot it and fix it then you are already half way through :)

Memory Allocation example for Double Pointer of a class

The following program should be self explanatory:



//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//Program to demonstrate memory allocation to double pointers
#include<iostream>

using namespace
std;

//Class named NewClass
class NewClass
{

public
:
int
a;
int
* b;
void
* c;
};


//List Structure containing multiple NewClass objects
struct NewClassList
{

int
numOfObjects;
NewClass** Objects;
};


int
main()
{

//Create NewClassList with 4 objects with following values:
//1, 10, 100; 2, 20; 200; 3, 30, 300; 4, 40, 400;
NewClassList someList;
someList.numOfObjects = 4;
//someList.Objects = new NewClass*; //1. Common mistake in allocating memory
someList.Objects = new NewClass*[someList.numOfObjects];

someList.Objects[0] = new NewClass;
someList.Objects[0]->a = 1;
someList.Objects[0]->b = new int(10);
someList.Objects[0]->c = (void*) new int(100);

someList.Objects[1] = new NewClass;
someList.Objects[1]->a = 2;
someList.Objects[1]->b = new int(20);
someList.Objects[1]->c = (void*) new int(200);

someList.Objects[2] = new NewClass;
someList.Objects[2]->a = 3;
someList.Objects[2]->b = new int(30);
someList.Objects[2]->c = (void*) new int(300);

someList.Objects[3] = new NewClass;
someList.Objects[3]->a = 4;
someList.Objects[3]->b = new int(40);
someList.Objects[3]->c = (void*) new int(400);

//Printing the outputs
for(int i = 0; i < someList.numOfObjects; i++)
{

cout<<"Iteration = "<<i;
cout<<": a = "<<someList.Objects[i]->a;
cout<<": b = "<<*(someList.Objects[i]->b);
cout<<": c = "<<*((int*)someList.Objects[i]->c)<<endl;
}


//Clear all the memory allocation
for(int i = 0; i < someList.numOfObjects; i++)
{

delete
someList.Objects[i]->b;
delete
someList.Objects[i]->c;
delete
someList.Objects[i];
}

delete
[] someList.Objects;
return
0;
}





The output is as follows:

The challenging 'Infinite loop' problem

Picked this one up from The C++ blog.

Consider the following program:



#include <iostream>

int
main()
{

int
i;
int
array[4];
for
(i=0; i<=8; i++)
{

array[i]=0;
}


return
0;
}


Most people including myself expect this program to crash. This is not the case. The reason being the way everything is stored on stack. In simple representation, the storage is something like this:



So when i = 6, value of i is reset to 0 and the loop continues forever.

After digging some information on stack, heap, etc. I found some useful info in C++ in 24 hours:

Programmers generally deal with five areas of memory:
  • Global name space
  • The free store (a.k.a. Heap)
  • Registers
  • Code space
  • The stack

Local variables are on the stack, along with function parameters. Code is in code space, of course, and global variables are in global name space. The registers are used for internal housekeeping functions, such as keeping track of the top of the stack and the instruction pointer. Just about all remaining memory is given over to the free store, which is sometimes referred to as the heap.

The problem with local variables is that they don't persist. When the function returns, the local variables are thrown away. Global variables solve that problem at the cost of unrestricted access throughout the program, which leads to the creation of code that is difficult to understand and maintain. Putting data in the free store solves both of these problems.

You can think of the free store as a massive section of memory in which thousands of sequentially numbered cubbyholes lie waiting for your data. You can't label these cubbyholes, though, as you can with the stack. You must ask for the address of the cubbyhole that you reserve and then stash that address away in a pointer.

The stack is cleaned automatically when a function returns. All the local variables go out of scope, and they are removed from the stack. The free store is not cleaned until your program ends, and it is your responsibility to free any memory that you've reserved when you are done with it.

The advantage to the free store is that the memory you reserve remains available until you explicitly free it. If you reserve memory on the free store while in a function, the memory is still available when the function returns.

The advantage of accessing memory in this way, rather than using global variables, is that only functions with access to the pointer have access to the data. This provides a tightly controlled interface to that data, and it eliminates the problem of one function changing that data in unexpected and unanticipated ways.

For this to work, you must be able to create a pointer to an area on the free store and to pass that pointer among functions. The pointer is created using new and once you are done with it you can free the memory using delete.

Initialising Arrays while doing 'new'

The example below shows how to initialise the array when you are dynamically alocating the memory with new:


//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
#include<iostream>

using namespace
std;

int
main()
{

//int* x = new int(10); - Common Bug for Array allocation
int *x = new int[5]; // Memory UnInitialised
int *y = new int[5]();

for
(int i = 0; i < 5; i++)
{

cout<<"x["<<i<<"]="<<x[0]<<endl;
cout<<"y["<<i<<"]="<<y[0]<<endl;
}


//delete x; - Another Common bug
delete[] x;
delete
[] y;
return
0;
}



The output is as follows:

Practical Example of Using Virtual Functions II

From the past few articles we have been discussing about Virtual
Functions.
Before taking up another topic for discussion I thought
of providing one more example of how and when virtual functions may be used.
So, here it is, a practical
example of virtual function.


As virtual functions and Run-Time
Polymorphism
goes hand-in-hand so the example here may also serve as
an example of the use of run-time polymorphism.



// Example to illustrate
// the use of virtual functions
// and run-time polymorphism
#include <iostream.h>

// -- SORT CLASS --
class sort
{
protected:
int *arr;
int num_elmnt;

public:
sort(int);
~sort();
void get_elmnt();
void show_elmnt();
virtual void do_sorting()=0;
};

// takes an argument
// which is the number of
// elements we want
sort::sort(int x)
{
num_elmnt=x;
arr=new int[num_elmnt];
}

sort::~sort()
{
// free up he allocated memory
delete []arr;
}

void sort::get_elmnt()
{
// input elements
cout<<"\nEnter Elements...";
for(int i=0;i<num_elmnt;i++)
{
cout<<"\n#"<<i+1<<":";
cin>>arr[i];
}
}

void sort::show_elmnt()
{
// display the elements
cout<<"\nElements are...";
for(int i=0;i<num_elmnt;i++)
{
cout<<"\n#"<<i+1<<":";
cout<<arr[i];
}
}
// -- SORT CLASS ENDS --

// -- BUBBLE SORT CLASS --
class bubble_sort : public sort
{
public:
// constructor only calls the
// base constructor with the
// parameter
bubble_sort(int x):sort(x){}

void do_sorting();
};

void bubble_sort::do_sorting()
{
int temp;

// do bubble sorting
for(int i=0;i<num_elmnt;i++)
for(int j=0; j<(num_elmnt-1); j++)
if (arr[j]>arr[j+1])
{
temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
// -- BUBBLE SORT CLASS ENDS --

// -- SELECTION SORT CLASS --
class selctn_sort : public sort
{
public:
// just call the base class
// constructor
selctn_sort(int x):sort(x){}
void do_sorting();
};

void selctn_sort::do_sorting()
{
int temp;

// do selection sorting
for(int i=0;i<(num_elmnt-1);i++)
for(int j=i+1;j<num_elmnt;j++)
{
if(arr[i]>arr[j])
{
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
};
// -- SELECTION SORT CLASS ENDS --

void main()
{
bubble_sort bubble(3);
selctn_sort selctn(5);
sort *ptr;

ptr=&bubble;
ptr->get_elmnt();
ptr->do_sorting();

ptr=&selctn;
ptr->get_elmnt();
ptr->do_sorting();

// again point to bubble
ptr=&bubble;
ptr->show_elmnt();

// again point to selctn
ptr=&selctn;
ptr->show_elmnt();
}


Related Articles:


Introduction to Linked Lists III

In the article Introduction
to Linked Lists
, we introduced the concept of linked list, the example
program was programmed to be able to add and display the elements in the linked
list. In reality only addition of elements to the linked list is not enough
to take the most out of linked list; we should be able to do other operations
such as insertion, deletion of elements etc.


This article would teach you to do such operation (insertion, addition, deletion
etc).


The program itself is quite big and has enough comments so I won’t discuss
anything here; rather I leave it up to you to understand all the operations
yourself!


  // -- Linked Lists --
// ------------------
// Example program to illustrate
// addition, insertion, deletion
// and display of nodes in the
// linked list

#include<iostream.h>

// node class, this will
// represent the nodes or elements
// of the linked list
class node
{
public:
int info;
node *link;
};

// declare global objects
node *start=NULL;

// function prototypes
void insert(int, int);
void add(int);
void display(void);
void del(int);
void free();

void main(void)
{
int ch,pos,num;

while(ch!=5)
{
cout<<"1> Add";
cout<<"\n2> Insert";
cout<<"\n3> Delete";
cout<<"\n4> Display";
cout<<"\n5> Quit\n";

cin>>ch;

switch(ch)
{
case 1:
cout<<"enter element:";
cin>>num;

add(num);
break;

case 2:
cout<<"enter pos:";
cin>>pos;
cout<<"enter element:";
cin>>num;
insert(pos,num);
break;

case 3:
cout<<"enter element to be deleted:";
cin>>num;
del(num);
break;

case 4:
display();
break;
}
}

// free-up the allocated
// memory
free();
}

// --FUNCTION--
// this function takes two
// arguments, 'loc' is the
// number of elements after
// which the new element having
// value 'inf' has to be inserted
void insert(int loc,int inf)
{
node *temp;
node *temp_new;
int i;

// if invalid, return
if(loc<=0) return;

temp=start;

// skip to the desired
// location where the node
// is to be added
for(i=1;i<loc;i++)
{
temp=temp->link;
if(temp==NULL)
{
cout<<"NOT POSSIBLE!";
return;
}
}

// allocate new node
temp_new=new node;
temp_new->info=inf;
// make it point to the
// respective node
temp_new->link=temp->link;
// make the prev. node where
// the new node is added, to
// point at the new node
temp->link=temp_new;
}

  // --FUNCTION--
// display all the data
// in the linked list
void display(void)
{
node *temp;
temp=start;

// traverse or process
// through each element
// and keep printing
// the information
cout<<"\nelements are...\n";
while(temp!=NULL)
{
cout<<temp->info<<endl;
temp=temp->link;
}
}

// --FUNCTION--
// adds node to the end
// of the linked list
void add(int inf)
{
node *temp1;
node *temp2;

// if the element to be added
// is the first element
if(start==NULL)
{
// allocate a new node
temp1=new node;
temp1->info=inf;
temp1->link=NULL;

// make start point at it
start=temp1;
}
// if not
else
{
temp1=start;

// find out the last element
while(temp1->link!=NULL)
temp1=temp1->link;

// allocate new node
temp2=new node;
temp2->info=inf;
temp2->link=NULL;

// make the last element
// of the list to point
// at the newly created node
temp1->link=temp2;
}
}

// --FUNCTION--
// takes the argument of the
// 'info' part of the node
// to be deleted
void del(int inf)
{
node *temp, *old;

temp=start;

// while list not empty
while(temp!=NULL)
{
// if match is found
if(temp->info==inf)
{
// if it is the
// first node
if(temp==start)
start=temp->link;

else
old->link=temp->link;

delete temp;
return;
}
else
{
// traverse through
// each node
old=temp;
temp=temp->link;
}
}
}

// --FUNCTION--
// free up the allocated memory
// used by the nodes of the
// linked list
void free()
{
// below is a bit confusing
// part.
// here all the nodes that
// we have allocated are
// being freed up
node temp;
while(start!=NULL)
{
// store the next node
// to the one being deleted
temp=*start;

// delete the node
delete start;

// retrieve the next node
// to be deleted
start=temp.link;
}
}

Good-Bye!


Related Articles:


Introduction to Linked Queues

In one of the article Introduction
to Linked Stacks
, I said that representing data structures such as
Stacks and Queues as arrays had one major problem that it can’t have more
than a predefined number of elements. To overcome this we used linked lists
to represent stacks. In this article we’ll use linked lists to represent
queues.


Below are some graphics that illustrate the addition and retrieval of elements
to and from the linked queue.



Addition of elements in the linked queue


FIG.: Addition of data to the linked queue




FIG.: Retrieval of elements from the linked
queue




I don’t think there is anything more that needs to be discussed, so let’s
have a look at the example program:


  // -- Linked Queues --
// C++ Example Program to
// illustrate the representation
// of queues as linked lists
#include<iostream.h>

// node class, this will
// represent the nodes or elements
// of the linked queues
class node
{
public:
int info;
node *link;
};

// declare global objects
node *front=NULL;
node *rear=NULL;

// function prototypes
void add(int);
int retrieve();
void free();

void main(void)
{
int ch=0,num;

while(ch!=3)
{
cout<<"1> Add";
cout<<"\n2> Retrieve";
cout<<"\n3> Quit\n";

cin>>ch;

switch(ch)
{
case 1:
cout<<"enter element:";
cin>>num;

add(num);
break;

case 2:
cout<<"\n\Retrieved: ";
cout<<retrieve();
cout<<"\n\n";
break;
}
}

// free up the memory
free();
}

// function to add new nodes
// to the linked queue
void add(int inf)
{
node *temp;

temp=new node;

temp->info=inf;
temp->link=NULL;

if(front==NULL)
{
rear=front=temp;
return;
}

rear->link=temp;
rear=rear->link;
}

// function to retrieve
// data from the linked
// queue
int retrieve()
{
node *temp;
int inf;

if(front==NULL)
{
cout<<"Queue Empty!\n";
return NULL;
}

inf=front->info;
temp=front;
front=front->link;

delete temp;
return inf;
}

// free the dynamic memory
// allocated in the form of
// nodes of the linked queue
void free(void)
{
// below is a bit confusing
// part.
// here all the nodes that
// we have allocated are
// being freed up
node temp;
while(front!=NULL)
{
// store the next node
// to the one being deleted
temp=*front;
// delete the node
delete front;

// retrieve the next node
// to be deleted
front=temp.link;
}
}

Good-Bye!


Related Articles:


Introduction to Linked Lists Part II

In the previous article Introduction
to Linked Lists
, we introduced the basic concept of linked list. To
make the program (an the article) as simple as possible, we discussed only the
addition and display of nodes in the linked list although necessary we didn't’t
discussed the deletion of node in that article.


In this article we will be discussing about the deletion of nodes from linked
lists.


Deletion of node (elements) from a linked list


The node to be deleted can be represented by many ways but here we will be
representing it by its info. So if we have the following linked list


Linked lists - Deletion of nodes




And we want to delete node1 then we will express it by its info part (i.e. 10).


The main theory behind deletion of nodes is pretty simple. We need to make
the link pointer of the node before the target node (to be deleted) to point
at the node after the target node. Suppose if we wish to delete node having
info as 10 from the above linked list then it will be accomplished as below:


Linked list - Deletion of nodes


Now since node1 is orphan and has no meaning, it can be deleted
to free-up memory as represented below:


Linked lists - node deleted to free-up memory


The following example program illustrates all this. Keep reading
the comments to understand what is happening where!


  // -- Linked Lists --
// ------------------
// Example program in C++
// to illustrate the most simple
// linked list
// NOTE: this program can do three
// operation [adding, deleting,
// and displaying] of data in a
// linked list
#include<iostream.h>

// node class, this will
// represent the nodes or elements
// of the linked list
class node
{
public:
int info;
node *link;
};

// declare global objects
node *start=NULL;

// function prototypes
void add(int inf);
void display(void);
void del(int);

void main(void)
{
int ch;

// input elements
while(ch!=0)
{
cout<<"enter element to be added:";
cout<<"\nenter 0 to stop...\n";
cin>>ch;

if(ch!=0) add(ch);
cout<<"\n\n";
}

ch=-1;

while(ch!=0)
{
cout<<"enter element to be deleted:";
cout<<"\nenter 0 to stop...\n";
cin>>ch;

if(ch!=0) del(ch);
cout<<"\n\n";
}

cout<<"elements are...\n";
display();

// below is a bit confusing
// part.
// here all the nodes that
// we have allocated are
// being freed up
node temp;
while(start!=NULL)
{
// store the next node
// to the one being deleted
temp=*start;
// delete the node
delete start;

// retrieve the next node
// to be deleted
start=temp.link;
}
}

void add(int inf)
{
node *temp1;
node *temp2;

// if the element to be added
// is the first element
if(start==NULL)
{
// allocate a new node
temp1=new node;
temp1->info=inf;
temp1->link=NULL;

// make start point at it
start=temp1;
}
// if not
else
{
temp1=start;

// find out the last element
while(temp1->link!=NULL)
temp1=temp1->link;

// allocate new node
temp2=new node;
temp2->info=inf;
temp2->link=NULL;

// make the last element
// of the list to point
// at the newly created node
temp1->link=temp2;
}
}

void display(void)
{
node *temp;
temp=start;

// traverse or process
// through each element
// and keep printing
// the information
while(temp!=NULL)
{
cout<<temp->info<<endl;
temp=temp->link;
}
}

// this function takes an
// argument which is the info
// of the node to be delted
void del(int num)
{
node *old;
node *target;

target=start;

while(target!=NULL)
{
// if node to be
// delted is found
if(target->info==num)
{
// if node to be deleted
// is the first node
// in the list
if(target==start)
start=target->link;

// if not
else
// then make the node
// prev. to the node
// to be deleted to
// point at the node
// which is after it
old->link=target->link;

// free-up the memory
delete(target);
return;
}
else
{
// traverse through
// each node
old=target;
target=target->link;
}
}
}

Related Articles:


Introduction to Linked Lists

We have been using arrays to store similar data linearly. While arrays are
simple to understand and easy to implement in common situations, they do suffer
from some drawbacks which are listed below:




  • Arrays have fixed dimensions, even if we dynamically allocate the dimension
    it remains constant throughout. So there is a limit to the number of elements
    it can store.




  • Operations such as insertion and deletion are pretty much difficult to
    implement and increases the overhead because these operations require elements
    in the array to be physically shifted.




Linked lists overcome these drawbacks and are commonly used to store linear
data.


Actually elements of linked lists (called as nodes) store two information,
data and the link (pointer) pointing to the next elements (node).


The elements (nodes) are linked sequentially with the help of link pointers.
So we can say that linked lists are collection of nodes which have data and
are linked sequentially so that all the nodes or elements are grouped together.


In programming sense, linked lists are classes whose general form is:


  class node
{
public:
data-type info;
node *link;
};

Here info stores the actual data while link stores the memory
address of the next node, which forms the link between the nodes.


Graphical Representation of a Node of a Linked List

FIG.: Graphical representation of a node


Following figure illustrates the growing of linked lists, the node which has
its link as NULL is the last element in the linked list.


Growing of linked list

FIG.: Linked lists grows like this


Let us now discuss a bit about how a linked list grows:




  1. We have a pointer that stores the memory address of the first element
    in the linked list, represented as the start pointer (of type node). It
    is NULL to begin with as we don’t have any element in the list.




  2. As an element is added, the start pointer is made to point at it and since
    for now the first element is the last element therefore its link is made
    to be NULL




  3. After the addition of each element the link pointer of the previously last
    element is made to point at new last element. This step continues…




In this way the number of nodes in a linked list can grow or shrink over time
as far as memory permits.


Below is the example program that illustrates linked lists. This program is
made as simple as possible and therefore it only performs the basic action (addition
of element) in the linked list.


  // -- Linked Lists --
// ------------------
// Example program in C++
// to illustrate the most simple
// linked list
// NOTE: It is designed so that it
// could only add nodes to the
// list and display them.
#include<iostream.h>

// node class, this will
// represent the nodes or elements
// of the linked list
class node
{
public:
int info;
node *link;
};

// declare global objects
node *start=NULL;

// function prototypes
void add(int inf);
void display(void);

void main(void)
{
int ch;

// input elements
while(ch!=0)
{
cout<<"enter element to be added:";
cout<<"\nenter 0 to stop...\n";
cin>>ch;

if(ch!=0) add(ch);
cout<<"\n\n";
}

cout<<"elements are...\n";
display();

// below is a bit confusing
// part.
// here all the nodes that
// we have allocated are
// being freed up
node temp;
while(start!=NULL)
{
// store the next node
// to the one being deleted
temp=*start;

// delete the node
delete start;

// retrieve the next node
// to be deleted
start=temp.link;
}
}

void add(int inf)
{
node *temp1;
node *temp2;

// if the element to be added
// is the first element
if(start==NULL)
{
// allocate a new node
temp1=new node;
temp1->info=inf;
temp1->link=NULL;

// make start point at it
start=temp1;
}
// if not
else
{
temp1=start;

// find out the last element
while(temp1->link!=NULL)
temp1=temp1->link;

// allocate new node
temp2=new node;
temp2->info=inf;
temp2->link=NULL;

// make the last element
// of the list to point
// at the newly created node
temp1->link=temp2;
}
}

void display(void)
{
node *temp;
temp=start;

// traverse or process
// through each element
// and keep printing
// the information
while(temp!=NULL)
{
cout<<temp->info<<endl;
temp=temp->link;
}
}

Good-Bye!


Related Articles:


Merging One Dimensional Arrays

Merging of two arrays means to form one big array from two small arrays, which
has element from both the arrays linearly.


Ex. if we have the following two arrays:


array1 [5] = {1,2,3,4,5}


array2 [5] = {6,7,8,9,10}


and we merge these two arrays to form an array merge_array, then it would have
these elements:



merge_array [5] ={1,2,3,4,5,6,7,8,9,10}


So, from this example we understand that the array which will hold the merged
elements should have a dimension equal to the sum of the dimensions of the two
discrete arrays.


It is no big deal to merge two arrays, we just need to sum up the dimension
of the arrays, and then allocate an array having that dimension.


Below is the example program that illustrates this.


Please go through the program to understand every bit of it. It is accompanied
with enough comments to make everything clear. While two arrays has been merged
here, you can easily modify it to merge as many arrays as you wish.


  // -- Array Merging --
// -- Program --
// -------------------
// Example program to illustrate
// the merging of arrays
#include<iostream.h>
// process.h is needed for
// the exit function
#include<process.h>

void main(void)
{
int i,j;

// declare pointers for the needed
// arrays
int *array1,*array2;
int *merge_array;

// variables for the sizes of the arrays
// given by the user
int size_array1,size_array2,size_array3;

// input the number of elements
// required, by the user
cout<<"enter no. of elements for array1:";
cin>>size_array1;
cout<<"enter no. of elements for array2:";
cin>>size_array2;

// calculate the no. of elements
// required for the merge_array
size_array3=size_array1+size_array2;

// allocate the required arrays
array1=new int[size_array1];
array2=new int[size_array2];
merge_array=new int[size_array3];

// terminate if there is a problem in
// memory allocation of the arrays
if(array1==NULL || array2==NULL || merge_array==NULL)
exit(1);

// input the array elements
cout<<"\nFirst Array:\n";
for(i=0;i<size_array1;i++)
{
cout<<"element "<<i+1<<":";
cin>>array1[i];
}

cout<<"\nSecond Array:\n";
for(i=0;i<size_array2;i++)
{
cout<<"element "<<i+1<<":";
cin>>array2[i];
}

// merging is being done here
for(i=0;i<size_array1;i++)
merge_array[i]=array1[i];
for(j=0;j<size_array2;j++)
merge_array[i+j]=array2[j];
// till here

for(i=0;i<size_array3;i++)
{
cout<<"\n";
cout<<"element "<<i+1<<":";
cout<<merge_array[i];
}

cout<<endl;

// free-up the memory
delete[] array1;
delete[] array2;
delete[] merge_array;
}

Good-Bye!


Related Articles:


Classes & Objects: Dynamic Memory Allocation

Just as variables of pre-def data type are dynamically allocated, same way
objects of class can also be dynamically allocated. While the method of doing
this is no different but the way members of such objects are accessed is a bit
different. This is why I thought of writing a separate article on it.


Before discussing any further, look at the program below:


  // Example Program in C++
#include<iostream.h>

// class
class myclass
{
// by default everything is
// private to the class
int var1, var2;
void add();

public:
int sum;

void input(int,int);
};

// function definitions
void myclass::input(int a, int b)
{
var1=a;
var2=b;
add();
}

void myclass::add()
{
sum=var1+var2;
}

// main function starts
void main(void)
{
myclass obj; // simple object

myclass *pobj; // pointer
// of type 'myclass'

pobj=&obj; // now 'pobj' pointer
// points to the object 'obj' of
// class 'myclass'

// members are accessed by the '.'
// operator
obj.input(10,20);
cout<<obj.sum;
cout<<endl;

// in case of pointers of class,
// members are accessed by the
// '->' arrow operator
pobj->input(30,40);
cout<<pobj->sum;
cout<<endl;
}

Did you notice the difference?


Members of the object of the class as you know are accessed like this:


object.membername;

While, in case of pointers of the class, the members are accessed like this:


objectptr->membername;

This is the difference I wanted to show you!


As in case of dynamic memory allocation, we have to declare pointer of the
class, therefore members of the dynamically allocated objects will be accessed
by the (->) arrow operator.


Arrays and pointers are closely related. While the members of the pointers
of objects are accessed by the (->) operator, in case of arrays of objects,
we have to use ‘.’ operator instead.


The example program below will clear the confusion, if any:


  // Example Program in C++
#include<stdio.h>
#include<iostream.h>
#include<process.h>

class employee
{
private:
char name[30];
int emp_no,age;
float salary, net_salary, tax;
void calculate();

public:
void input();
void output();
};

//----FUNCTION DEFINITION STARTS----
void employee::input()
{
printf("Enter Name: ");
gets(name);
printf("Enter Employee Number: ");
cin>>emp_no;
printf("Enter Age: ");
cin>>age;
printf("Enter Salary: ");
cin>>salary;
printf("Enter Tax Paid: ");
cin>>tax;
printf("\n\n");

calculate();
}

void employee::output()
{
printf("Name: %s\n", name);
printf("Age: %d\n", age);
printf("Employee Number: %d\n", emp_no);
printf("Net Salary: %f\n", net_salary);
printf("\n\n");
}

void employee::calculate()
{
net_salary=salary-tax;
}
//----FUNCTION DEFINTION ENDS----

// main function starts
void main(void)
{
employee *emp_obj;
int num_emp;

printf("Enter Number of Employees: ");
cin>>num_emp;

emp_obj=new employee[num_emp];
// terminate if memory allocation
// failed
if(emp_obj==NULL) exit(1);

// take input
for(int i=0;i<num_emp;i++)
// object are accessed as arrays
// so '.' operator is used
// we can also write
// (emp_obj+i)->input(); to do the
// same thing
emp_obj[i].input();

printf("\n\n EMPLOYEE DETAILS\n");

// give output
for(i=0;i<num_emp;i++)
emp_obj[i].output();
}

As in the comments, we can either use


   emp_obj[i].input();
or
(emp_obj+i)->input();

to do the same thing, in the first case the object is referenced as an array
while in the other case, it is referenced as pointer. So the appropriate operator
is used in each case.


Hope this article helps!

A Multi-Purpose String Class in C++

NOTE: Here I present you with a String Class in C++. We have
pre-defined string class (CString in Microsoft Visual C++) which has similar but
more powerful to the one presented here but using something is one thing and learning
how it works is another. Here I show you how string functions actually work. All
the functions are programmed from the scratch without using any other standard
library function. Look at the program (Class) carefully and try to understand
how each of the function is working.

  //-----------------------------
//-----------myClass-----------
//----A String Class in C++----

#include<iostream.h>
#include<stdlib.h>

class myString
{
private:

// these functions are not
// needed outside the class
void allocate(int);
void copy(char *, char *);

public:

   char *string;

// member functions
myString();
myString(char *);
int getLength();
int getLength(char *);
void empty();
bool isEmpty();
void putString(char *);
char *getString();
char *fromLeft(int);
char *fromRight(int);
char *fromMid(int, int);
~myString();
};

//--------------------------------
//------------MEMBER--------------
//---FUNCTION DEFINITION STARTS---
void myString::allocate(int size)
{
empty();

string=new char[size];
if(string==NULL) exit(0);
}

void myString::copy(char *str1, char *str2)
{
int length=getLength(str2);

for(int i=0;i<=length;i++)
str1[i]=str2[i];
}

void myString::empty()
{
if(string!=NULL)
{
delete []string;
string=NULL;
}
}

bool myString::isEmpty()
{
if(string!=NULL)
return false;

return true;
}

int myString::getLength(char *str)
{
int i=0;

while(str[i]!='\0')
i++;

return i;
}

int myString::getLength()
{
if(string!=NULL)
return getLength(string);

return -1;
}

myString::myString(char *str)
{
string=NULL;
int size=getLength(str)+1;

allocate(size);

copy(string,str);
}

myString::myString()
{
string=NULL;
}

void myString::putString(char *str)
{
int size=getLength(str)+1;

allocate(size);

copy(string,str);
}

char *myString::getString()
{
if(string!=NULL)
{
return string;
}
}

myString::~myString()
{
if(string!=NULL)
delete []string;
}

char *myString::fromLeft(int chr)
{
if(string!=NULL)
{
char *temp;
temp=new char[chr+2];

if(temp==NULL) exit(1);

for(int i=0;i<chr;i++)
temp[i]=string[i];

temp[i]='\0';
return temp;
}
}

char *myString::fromRight(int chr)
{
if(string!=NULL)
{
char *temp;
temp=new char[chr+2];
int a=0;

if(temp==NULL) exit(1);

int i=getLength()-1;
int j=(i-chr)+1;

for(j;j<=i;j++)
{
temp[a]=string[j];
a++;
}
temp[a]='\0';
return temp;
}
}

char *myString::fromMid(int a,int b)
{
if(string!=NULL)
{
int size=b+1;
char *temp;
temp=new char[size];
int i=a,j=0,k=(a+b);

for(i;i<k;i++)
{
temp[j]=string[i];
j++;
}
temp[j]='\0';
return temp;
}
}
//-----------MEMBER-------------
//---FUNCTION DEFINITION ENDS---
//------------------------------

void main(void)
{
myString a("Learning C++ Programming");

cout<<a.getString();
cout<<endl;
cout<<a.fromLeft(3);
cout<<endl;
cout<<a.fromRight(3);
cout<<endl;
cout<<a.fromMid(3,3);
cout<<endl<<a.isEmpty();

a.empty();
// will not print anything
cout<<endl<<a.fromLeft(3);
// will print true(0)
cout<<endl<<a.isEmpty();
}


Good-Bye for now!


Check back for updates...

Introduction to Dynamic Memory Allocation in C++

Suppose you are making a C++ program to store a particular number (specified
by the user at runtime) of phone numbers. What will you do? You cannot declare
array of 10 or 20 elements because you don’t know how many numbers the
user will enter. He may want to enter 1, 10 or even 100 phone numbers.


So what will you do?


Actually, you can do two things to achieve this, that are listed below:




  1. You can create a very large int(eger) array (say, of 500 elements) , in
    this case whether the user wants to store 1 or 500 phone numbers, the memory
    used will always be the same (large!).




  2. You can make use of C++’s dynamic memory allocation to allocate only
    the needed amount of memory.




The first choice is a very bad way of programming, nevertheless it works fine,
you should never employ such an inefficient method of programming.


So, you are left with only one choice to use the Dynamic Memory Allocation
of C++ programming language, that I will be discussing in this article.


As is clear from the above example, dynamic memory allocation is needed when
you don’t know the program’s memory needs beforehand.


Allocating Memory


Dynamic memory is allocated by the new keyword. Memory for
one variable is allocated as below:


ptr=new DataType (initializer);

Here,




  • ptr is a valid pointer of type DataType.




  • DataType is any valid c++ data type.




  • Initializer (optional) if given, the newly allocated variable is initialized
    to that value.




Ex.


  //Example Program in C++
#include<iostream.h>

void main(void)
{
int *ptr;
ptr=new int(10);


cout<<*ptr;

delete ptr;
}

This is will allocate memory for an int(eger) having initial value 10, pointed
by the ptr pointer.


Memory space for arrays is allocated as shown below:


ptr=new DataType [x];

Here,




  • ptr and DataType have the same meaning as above.




  • x is the number of elements and C is a constant.




Ex.


  //Example Program in C++
#include<iostream.h>

void main(void)
{
int *ptr, size;

cin>>size;
ptr=new int[size];

//arrays are freed-up like this
delete []ptr;
}

Freeing-Up Allocated Memory


Unlike static variables, c++ will not free-up the memory allocated through
dynamic allocation. Its your duty to free them up. delete keyword
is used to free-up the allocated memory.


delete ptr;

Arrays are deleted in a slightly different manner as shown below:


delete []ptr;

It’s easy to forget to free the allocated memory because C++ compiler
won’t inform you that you are doing this. It’s your job and should
always be done.


Now let me show you an example of dynamic memory allocation in action:


  //Example Program in C++
#include<iostream.h>

void main(void)
{
int *ptr, size;

cout<<"How many PH. Numbers do you wish to enter:";
cin>>size;
ptr=new int[size];//allocate memory

//input ph. numbers
for (int i=0;i<size;i++)
{
cout<<"Enter PH. NO."<<i+1<<" :";
cin>>ptr[i];
}

//output ph. numbers
cout<<"\n\n\n PH. NOs. are\n";
for (i=0;i<size;i++)
cout<<"\nPH. NO."<<i+1<<" :"<<ptr[i];

cout<<endl;

delete []ptr;//free-up memory
}

Good-Bye!


Related Articles:


Check out this stream