?
Solved

c++ Memory leak

Posted on 2012-09-18
7
Medium Priority
?
489 Views
Last Modified: 2012-10-05
Hi,

I have a c++/CLI dll, this dll is used by a c# client to calculate data. When i run the call multiple times in succession i get a 'corrupted memory' exception (System.AccessViolationException). This exception occurs on the same iteration every time (Inputs can vary) so i believe it is caused by a memory leak.

I've used #define _CRTDBG_MAP_ALLOC to try to pinpoint potential issues, however the output from this simply shows that objects which are created during initialisation and designed to be held in memory for reuse are not cleared (as i would expect to happen)

My main c++ creates this storage in the constructor and should only release it when the c# client app is finished, so memory seems to be as i would expect.

Is my whole thought process wrong here?
0
Comment
Question by:basil365
  • 4
  • 2
7 Comments
 

Author Comment

by:basil365
ID: 38409554
Also when running in release mode the app constantly fails when looking up a value in one of these storage arrays. this array is defined to be created the heap

double * normalTime;// = new double[136800];

Open in new window


because of the size - could this be causing the issue?
0
 

Author Comment

by:basil365
ID: 38409574
Dang - error occurs in the same place after changing to 'double normalTime[136800];'
0
 
LVL 35

Expert Comment

by:sarabande
ID: 38409869
memory leaks would not directly cause access violation. only if no more (contiguous) memory is available the new operator might return NULL pointers what could crash if not handled. but if that is the case you should be able to see the lack of available memory in task manager. and obviously it is not the above array cause arrays defined on the stack would not crash at runtime beside you access them beyond their boundaries.

corrupted memory easily could occur. you simply need to return and use a pointer to local memory (locally defined in a function) and it would crash at least when you enter the function next time. or if the calls to the dll are from multiple threads, you easily could get crashes if your functions are not thread-safe.

can you post the code for the iteration you think the crash was happening and also the code where the pointers used were assigned?

Sara
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:basil365
ID: 38409977
Thanks for the reply Sara,

This is the pure c++ class that holds the storage:

#ifndef DISTRIBUTIONS_H
#define DISTRIBUTIONS_H

#include "DistType.h"
#include <math.h>
#include "IndexTools.h"

/*
Class to store all Distributions and Parameters needed
by the model. These are loaded from a database and stored
as doubles and double arrays.
*/
class Distributions
{
public:
        double * normalTime;// = new double[136800];

	int NormalTimeLookup(int i, int j, int k, int l, int m, int n);

        double Distributions::RunNormalTime(int Q, int T, int D, 
	int len, int F, int def)
   
        bool Setup()

private:
	bool loaded;

};

#endif

Open in new window


There are more attributes, but there are of a similar format

This is the implementation file:

#include "stdafx.h"
#include "Distributions.h"
#include <assert.h>

/*
Destructor: Allocated space on heap for members
*/
Distributions::Distributions()
{

	normalTime = new double[136800];
}

/*
Destructor: Clean up heap-allocated members
*/
Distributions::~Distributions()
{

	delete [] normalTime;

	
	cout << "Distribution destoyed" << endl;
}

int Distributions::NormalTimeLookup(int i, int j, int k, int l, int m, int n)
{
	return IndexTools::GetIndexFrom6D(i, j, k, l, m, n, 2, 19, 4, 3, 100, 3);
}

double Distributions::RunNormalTime(int Q, int T, int D, 
	int len, int F, int def)
{
	double x[4];
	int xLength = 4;

    if (Q == 2 && T > 720)
    {

		int index = this->NormalTimeLookup(1, (int)round(T / 10.0) - 72, D - 1, len, F, max(min(def, 1), -1) + 1);
		return normalTime[index];
		

 }
return 0;

}

bool Distributions::Setup()
{
	bool success;
	if(!this->loaded)
	{
		bool dLoaded =  LoadDistributions();
		bool pLoaded =  LoadParameters();
		bool dCreated = CreateDistributions();
	
		success = dLoaded && pLoaded && dCreated;

		this->loaded = success;
	}

	return success;
}

Open in new window


Setup initialises the values held in storage

I then have a CLI wrapper class which simply forwards a call from c# to the above class (and others. The above storage class's constructor is called when this wrapper is first created:

	
Simulator::Simulator()
	{
		this->sim = new Simulator();
		this->sim->distrs = new Distributions();
		this->loaded = this->sim->distrs->Setup();
	}

Open in new window


and the destructor should clear the mem

	
//Clean up 
	Simulator::~Simulator()
	{
		delete this->sim->distrs;
		delete this->sim;
	}

Open in new window


in c# i simply have a loop (this was added to try to find the issue) that sequentially calls the wrapper

Simulator simulator = new Simulator();

for (int i = 0; i < 3600; i++)
            {
                try
                {


                    SetInputValues(input);
                    DateTime start = DateTime.Now;
                    output = simulator.Simulate(input);
                    DateTime end = DateTime.Now;

                    TimeSpan s = end - start;
                    Console.WriteLine(s.TotalMilliseconds);
                    Console.WriteLine(output.matchBetting[0]);
                    Console.WriteLine(output.matchBetting[1]);

                }
                catch
                {
                }

            }

Open in new window

0
 
LVL 35

Expert Comment

by:sarabande
ID: 38410486
i don't understand

Simulator::Simulator()
{
    this->sim = new Simulator();

Open in new window


in my opinion the above would infinitely create new pointers.

another crucial thing is that the index calculation always keeps within range. you definitively would need to make a check on that before accessing the array.

Sara
0
 

Author Comment

by:basil365
ID: 38410713
Thanks - the above is a typo when i was stripping down the code - its basically a helper class that utilises the storage class

I'll add in that check, although i added a conditional breakpoint to the point where we retrieve the index and it seems that the value is always set to 0.

from my app point of view this is obviously incorrect, but i dont see how  it would cause any failures at this point then?
0
 
LVL 9

Accepted Solution

by:
Subrat (C++ windows/Linux) earned 1000 total points
ID: 38411003
I' agree upon  sarabande's comment on using this->sim = new Simulator() in constructor....

Definitely it'd fall in heap overflow.....So you need to avoid this.
0

Featured Post

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Container Orchestration platforms empower organizations to scale their apps at an exceptional rate. This is the reason numerous innovation-driven companies are moving apps to an appropriated datacenter wide platform that empowers them to scale at a …
Hello there! As a developer I have modified and refactored the unit tests which was written by fellow developers in the past. On the course, I have gone through various misconceptions and technical challenges when it comes to implementation. I would…
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.
Suggested Courses

829 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question