Skip to main content

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; 

How to Learn Windows Phone 8.1 apps development

· One min read

Videos

Beginners Windows Phone 8.1 development You need the Absolute Beginner Series for Windows Phone 8.1 It is a complete course in getting started for Windows Phone 8.1. source code for all the projects here.

Overview of the features available in Windows Phone 8.1 Watch the first session of the Jump Start.

Want to learn what is new  WP 8.1 You need the Building Apps For Windows Phone 8.1 Jump Start. source code is available here.

Blogs

1. https://dev.windowsphone.com/en-us/develop

2. Windows Phone 8.1 for Developers–What Controls Are New

Windows Phone 8.1 Development

· 2 min read

Software

  • The Windows Developer Center is your base for all things Windows and Windows Phone related http://dev.windows.com http://dev.windowsphone.com
  • FREE Download: Visual Studio Express 2013 for Windows
  • Visual Studio Express 2013 allows to develop apps for Windows 8.1 and Windows Phone 8.1
  • Developers using Visual Studio 2013 Professional or higher has to install Visual Studio 2013 Update 2 to add in Windows Phone 8.1 dev tools

PC (Hardware) Requirements

Operating systemsWindows 8.1 (x86 or x64)
Hardware4GB of free disk space1.5 GB of RAM (recommended)64-bit (x64) motherboard
Windows Phone EmulatorsWindows 8.1 Pro or higher (for Hyper-V) and Second Level Address Translation (SLAT)Minimum 4GB RAM

Windows Developer Account

For starting development of app you do not need Developer Account. For publishing Windows Phone and/or Windows Store apps you need to get the Developer Account

To get a Developer Account: Included if you have an MSDN subscription Free to students who have a Dreamspark subscription $19 charge per annum for individual developers, $99 for Company accounts

Approaches to develop Windows Phone 8.1 app

· 2 min read

There are three approaches to develop Windows Phone 8.1 apps XAML Apps. I like third 'Use Windows XAML platform' approach as most of the users upgrade WP8 to WP8.1.

ApproachPros & Cons
Keep using Silverlight 7.x/8(Windows Phone 8 platform)Pros
  • Will run on Windows Phone 8.1 and also runs on earlier Windows Phone devices
Cons
  • No new platform capabilities
  • Will not enable targeting of Windows
Use Silverlight 8.1 (Move Silverlight app into new execution stack and app package)Pros
  • Enables to use new APIs and platform capabilities
Cons
  • Will not enable targeting of Windows
  • Will not run on Windows Phone 8 devices
Use Windows XAML platformPros
  • Enables targeting of Windows and Windows Phone
  • Takes full advantage of new APIs and platform capabilities
  • Better performance
  • Reduced memory use
Cons
  • Will not run on Windows Phone 8 devices

What's new in Windows Phone 8.1 Hardware

· One min read
  • Dual-SIM works in Windows Phone 8.1 by splitting out the phone dialer and messaging into two separate Live Tiles.
  • Decrease HW cost floor (support 8x26, Qualcomm Reference Design)
  • Apps can be installed on microSD
  • Apps to help you get more out of your data plan: DataSense 2.0, Wi-Fi Sense, Storage Sense, Battery Sense
  • Virtual softkeys instead of capacitive keys.

New Features in Windows Phone 8.1

· One min read

For Users

  • Customize Start screen: Customize your Start screen background with a favourite picture or one of the supplied options. Users can configure three column start screen which is available on all phones. Start screen backup and restore feature is also available.

  • PERSONAL Digital Assistant CORTANA: CORTANA learns about you and your interests Enables CORTANA to be proactive and helpful throughout the day

  • Action center to quick launch settings and view notifications

  • Fast typing with new Word Flow keyboard

  • Buy app once: use on PC and on Phone

  • App data can roam among devices

  • App data backup

  • Faster app updates

  • Remote viewing of Phone screen

  • Install apps to SD card

  • New Skype app integrated with Phone dialer

  • New Calendar app with new Week view

For Developers

  • Converged developer platform
  • Converged app model
  • Shared app identities + entitlement
  • Unified push services (via WNS)
  • Live tile improvements
  • Action Center for smart notifications
  • Internet Explorer 11 improvements
  • Background execution + triggers
  • Bluetooth-LE support for wearables + beacons

Microsoft Surface Pro 3 Launch

· One min read

Microsoft Surface Pro 3 is a thin tablet which replaces your laptop, more productive, Beautiful screen, Faster than Surface Pro 2

Live webcast @ http://www.microsoft.com/en-us/news/press/2014/may14/05-20webcast.aspx

Thicknesses : 9.1 mm

Screen : 12.0"

Weight : 800g

Processor : Core i7 Fan less

Estimated price of Surface Pro 3:

  • 4th gen Intel® Core™ i3, 64 GB and 4 GB of RAM - $799

  • 4th gen Intel® Core™ i5, 128 GB and 4 GB of RAM - $999 4th gen Intel® Core™ i5, 256 GB and 8 GB of RAM - $1,299

  • 4th gen Intel® Core™ i7, 256 GB and 8 GB of RAM - $1,549 4th gen Intel® Core™ i7, 512 GB and 8 GB of RAM - $1,949

Upgrade from Windows Phone 8 to Windows Phone 8.1

· One min read

If you have a Windows Phone 8 now and want to get the preview of Windows Phone 8.1:

NOTE:

  • Warranty will break

- You CANNOT REVERT to a prior OS version once you have taken an update via this program

Microsoft Remote Desktop Preview for Windows Phone 8.1

· One min read

Microsoft Remote Desktop Preview now available for Windows Phone 8.1

If you install Windows Phone 8.1 preview for developers on your phone.

It's time to download and try 'Microsoft Remote Desktop Preview' app which is now available in WP Store

Features

  • Rich multi-touch experience with Remote Desktop Protocol (RDP) and RemoteFX supporting Windows gestures
  • Secure connection to your data and applications with breakthrough Network Level Authentication (NLA) technology
  • Simple management of all remote connections from the connection center
  • High quality video and sound streaming with improved compression and bandwidth usage

Release 8.1.1 includes the following updates:

  • Pin desktop connections to the Start screen
  • Support for word flow and predictive text
  • Ability to disable thumbnails

Bring your App Studio apps to Windows 8

· One min read

Windows Phone App Studio Beta is awesome. It’s a great way to build your first app for Windows Phone. It lets you choose different design templates and styles, and lets you pull in different data sources, from RSS feeds, to YouTube, to Flicker or even Bing. In this post, we’ll talk about how to take an app that you created in App Studio go further by making it work on Windows 8 using the latest update to Windows Phone App Studio.

For More Info read this->