Skip to main content

25 posts tagged with "C++"

View All Tags

Abstract Class

· 2 min read

Abstract classes are used for providing an abstraction to the code to make it reusable and extendable.

Abstract class in C++

It is a class that has at least one pure virtual function (i.e., a function that has no definition). The classes inheriting the abstract class must provide a definition for the pure virtual function.

How to avoid Memory Leaks in C++, VC++"

· 4 min read

Contents

  1. Introduction
  2. How to find memory leak
  3. Memory Leak and how to avoid it

Updated on : 17-Oct-2014

1. Introduction

The failure to properly deallocate memory that was previously allocated is known as Memory Leak. The consequences of memory leaks is that the programs that leak large amounts of memory, or leak progressively, may display symptoms ranging from poor (and gradually decreasing) performance to running out of memory completely. Worse, a leaking program may use up so much memory that it causes another program to fail, leaving the user with no clue to where the problem truly lies. In addition, even harmless memory leaks may be symptomatic of other problems.

2. How to Find Memory Leak

Use third-party tools like DevPartner or use the following steps to find the memory leaks

  • Compile the project in "Debug" Mode.
  • Declare the objects CMemoryState msOld, msNew, msDif;
  • Check the memory state at one point. msOld.Checkpoint(); ://code ://code
  • Check the memory state at onother point. msNew.Checkpoint();
  • See for Difference msDif.Difference( msOld, msNew );
  • Display the Leaked blocks in Debug window  msDif.DumpStatistics();

3. Memory Leak and How to avoid it

a. Wrong usage of new/delete.

int* intArr; 
intArr = new int[500];
delete intArr;

Use  delete[]intArr; instead of delete intArr as delete intArr is equal to deleting intArr[0];

b. Improper deletion of Array of Pointers

introwNo = 3; 
intcolsNo = 3;
int *array = new int[rowNo];

for(inti=0; i < rowNo; i++) {
array[i] = new int[i+1];
}

delete[] array;

The cause of memory leak is that the 'array' is an array of pointers, with each of it's elements pointing to a separate memory block, so it is necessary free these blocks before freeing the array that holds the pointers.

for(int i=0; i < rowNo; i++) 
{
delete[] array[i];
}

delete [] array;

c. Resource Handles: GDI Objects- CBrush, CPen, CFont, CBitmap, CPallete, CRgn and respective handles

CBrush myBr, *pOldBr; 
myBr.CreateSolidBrush(RGB(0, 255, 0));
pOldBr = pDC->SelectObject(&myBr);
pDC->SelectObject(& myBr );
pDC->SelectObject(pOldBrush);

For more details Check:http://msdn.microsoft.com/en-us/library/windows/desktop/ms724291(v=vs.85).aspx

The DeleteObject method deletes the GDI object by freeing all system storage associated with it. The storage associated with the CGdiObject object is not affected by this call. An application should not call DeleteObject on a CGdiObject object that is currently selected into a device context. Use myBr.DeleteObject(); after finishing using myBr (Cbrush) object For handles pass handle of the DeleteObject function DeleteObject(hPen);

d. String conversions CString to LPTSTR

CString sName; 
sName= _T("Hello");
int lenName = sName.GetLength();
LPTSTR lpstrg = sName.GetBuffer(lenName);

sName.ReleaseBuffer();
Cstring to BSTR CString csStr = "Hello";
BSTR bStr = csStr.AllocSysString();

SysFreeString(bStr); //finished using the BSTR

Use ReleaseBuffer() when ever we create a buffer. Use SysFreeString() when ever we use AllocSysString() which allocates a new string of the type BSTR.

e. Improper deletion of pointer objects in a CList

CList<CMyData, CMyData> ptList;
CList<CMyData, CMyData> ptList;
ptList.RomoveAll(); //Improper deletion of pointer objects in a CArray CArray<CMyData, CMyData> ptArr;
ptArr.RemoveAll();

Proper deletion of pointer objects in a CList

CList<CMyData, CMyData> ptList;
POSITION pos = ptList.GetHeadPosition();

while(pos!=NULL) {
delete ptList.GetNext(pos);
}

PtList.RomoveAll();

// Proper deletion of pointer objects in a CArray CArray<CMyData_, CMyData_\> ptArr; : : int i = 0;

while(i<ptArr.GetSize()) {
delete ptArr.GetAt(i++);
}

ptArr.RemoveAll();

f. Opening and proper closing of file and databases

CFile file; 
file.Open(szFilePath, CFile::modeCreate | CFile::modeWrite, 0);
file.Write(chFile, chFileSize);
file.Close();

e. Usage of Static Arrays

int Sample[500]; 

Never use static arrays if the array is dynamically growing. Instead of using static arrays use CArray or OCArray Example:

 CArray<int, int> Sample; 

what is the output

· One min read
# include <iostream>

using namespace std;

int main() {
int a=10,b=2;
b = a+++a;
cout<<b<<" "<<a<<"n";
return 0;
}

OUTPUT 20 11
Tags:

C-Pointers What is the output

· One min read

FAQ-1

void main() { 
int _p = 91; //compilation error
printf("%d n",_ p);
printf("%d n", p);
}

OUTPUT: Does not compile error C2440: 'initializing' : cannot convert from 'int' to 'int *'

FAQ-2

void main() { 
int i = 91; int *p = &i;
printf("%d n", *p); printf("%d n", p);
}

OUTPUT: 91 1245024

FAQ-3

void main() { 
int i = 91;
int *p = &i;

printf(" p = %d n",p);
printf(" p = %d n", p);
printf(" &p = %d n", &p);
printf(" (&p) = %d n", (&p));
printf(" ((&p)) = %d n", ((&p)));
}

OUTPUT: i = 91 &i = 1245024 p = 91 p = 1245024 &p = 1245012 (&p) = 1245024 ((&p)) = 91

FAQ-4

void main() { 
const int p;
int i;
i = 10;
p = &i;
printf("p = %d, p = %d, i = %d", p, p, i);
}

OUTPUT p = 1245012, p = 10, i = 10
Tags:

Find the length of the string in C

· One min read
//str_len returns the length of str
int str_len(char* str) {
int len; len = 0;
for (int i = 0; str[i] != '\\0'; i++)
{
len ++;
}
return len;
}

void main() {
char* website = "www.github.com";
int len = str_len(website);
printf("length = %d n", len);
}

OUTPUT length = 17
Tags:

Unit Testing Native C++ App with out clr

· One min read

Unit Testing Native C++ Applications with out “/clr” flag or fall back to 3rd party frameworks

Visual Studio 11 provides the ability to do Unit Testing Native C++ Applications with a new C++ unit testing framework shipping with VS 11.

So the C++ developers no longer need to use the “/clr” flag or fall back to 3rd party frameworks.

To learn more about native unit testing in Visual Studio 11, please visit MSDN.

Part-1: C++, C#, Java Syntax Differences

· One min read

C++ Main Function

  1. Main function with out any arguments
void main() { 
cout<<"Hello World !!!";
}
  1. Main function with commandline Arguments
int main(int argc, char* argv[]) {
cout<<"Hello World !!!";
return 1;
}

C# Main Function

  1. Main function with out any arguments
using System; 
namespace CSharpSample {
class Program {
static void Main() {
Console.WriteLine("Hello World !!!");
}
}
}
  1. Main Function with commandline Arguments
 using System; 
namespace CSharpSample {
class Program {
static int Main(string[] args) {
Console.WriteLine("Hello World !!!");
return 1;
}
}
}

Java Main function

  1. Main function with out any arguments Not possible Compilation error java.lang.NoSuchMethodError: main Exception in thread "main" Main function with commandline Arguments

  2. Main Function with commandline Arguments

public class Program { 
public static void main(String args[]) {
System.out.println( "Hello, World !!!" );
}
}

Part-2: C++, C#, Java Syntax Differences

· 2 min read

[Part-2: Basic Input/Output] C++, C#, Java Syntax Differences

Basic Input/Output

Using the standard input and output library, we will be able to interact with the user by printing messages on the screen and getting the user's input from the keyboard.

1. C++

  • Input    - cin>>
  • Output - cout<<
// Print Greetings Program
// Basic Input/Output
void PrintGreeting(char name[])
{
cout<<"Hello " << name <<endl;
}

int main(int argc, char* argv[])
{
char name[100\];

cout<<"Enter Your Name:"; //cout -> Standard Output
cin>>name; //cin -> Standard Input

PrintGreeting(name);

return 1;
}

/* OUT PUT
Enter Your Name:nagvbt
Hello nagvbt
*/

2. C#

  • Input  - Console.WriteLine()
  • Output - Console.ReadLine()
// Print Greetings Program
// Basic Input/Output
namespace CSharpSample
{
class Program
{
static void PrintGreeting(char[] name)
{
Console.WriteLine("Hello "+ new string(name));
}

static int Main(string[] args)
{
char[] name;

Console.WriteLine("Enter Your Name:"); //Console.WriteLine() -> Standard Output
string sName = Console.ReadLine(); //Console.ReadLine() -> Standard Input
name = sName.ToCharArray();

PrintGreeting(name);

return 1;
}
}
}

/* * OUTPUT * *
Enter Your Name:
Nag VBT
Hello Nag VBT
* * * * * * * */

3. Java

Input - System.out.println()

Output - System.in.read()

import java.io.IOException;

class Program
{
public static void PrintGreeting(char[] name)
{
System.out.println("Hello "+ new String(name));
}

public static void main(String[] args)
{
char[] name;

System.out.print("Enter Your Name:"); //System.out.println -> Standard Output

String sName = "";
int tmp;
try
{
while((tmp = System.in.read ()) != 'n') // System.in.read -> Standard Input
{
char c = (char) tmp;
sName = sName + c;
}

}
catch (IOException e)
{
e.printStackTrace();
}

name = sName.toCharArray();
PrintGreeting(name);
}
}

/* OUTPUT
Enter Your Name:Nag VBT
Hello Nag VBT
*/

Part-3: C++, C#, Java Syntax Differences

· One min read

Comments, Methods, Class, objects Syntax Differences

Comments Same for C++, C#, Java

  1. Single line comments  - //
  2. Multi line comments

/ This is a a multiline comment /

Method/Function declarations

Same, except that in C# and in Java, function must always be part of a class, and must prefix with access specifier - public/private/protected

check main function for reference

Class declarations

Same but c# and Java does not require a semicolon after closing bracket '}'

_ C++ _

class myMath {
//Methods
public: int Add(int i, int j)
{
return i + j;
}
};

_ C#/Java _

 class myMath {
//Methods
public int Add(int i, int j)
{
return i + j;
}
}

Object declaration/creation C++

Object creation on Stack

myMath obj; //on stack
int result = obj.Add(1,2);

Object creation on Heap

myMath \*pobj = new myMath(); //on heap
int result = obj->Add(1,2);
delete pobj;

Java/C#

myMath obj = new myMath();
int result = obj.Add(1,2);