From: Paolo on
Hello all,

I created successfully a mex file. It is linked to an external dll and it worked fine (it returns correctly to matlab a vector). Recently I added an new function inside my c++ file which does not affect the result of the c++ function but is just used to improve some data manipulation. By the way, this function works quite well in a simple c++ file and I have already used many times in other c++ files (no-mex files).
After added this function my matlab crashes and returns me this error:


MATLAB crash file:C:\DOCUME~1\MILCEMEA~1.VAA\LOCALS~1\Temp\matlab_crash_dump.2996
------------------------------------------------------------------------
Segmentation violation detected at Wed Jul 28 18:38:04 2010
------------------------------------------------------------------------

Operating System: Microsoft Windows XP
Window System: Version 5.1 (Build 2600: Service Pack 3)
Processor ID: x86 Family 6 Model 7 Stepping 10, GenuineIntel
Virtual Machine: Java 1.6.0_04-b12 with Sun Microsystems Inc. Java HotSpot(TM) Client VM mixed mode
Default Encoding: windows-1252

Fault Count: 1

Register State:
EAX = ffff5df8 EBX = 00c2e01c
ECX = ffffffff EDX = e06d7363
ESI = ffff5df4 EDI = 04f169ec
EBP = 00c2e028 ESP = 00c2cf40
EIP = 04ec186e FLG = 00010286

Stack Trace:
[0] qlDiscountFactors.mexw32:0x04ec186e(0x00c2e158 "x£", 0x00c2e0b8, 0x00c2e1fc, 0)
[1] 0x00c2e20c(0x8b00032b, 0x04c483d8, 0x85e85d89, 0xb7840fdb)

This error was detected while a MEX-file was running............

Any suggestion???
thanks in advance
From: Paolo on
"Paolo " <tarpanelli(a)libero.it> wrote in message <i2pnkr$gt7$1(a)fred.mathworks.com>...
> Hello all,
>
> I created successfully a mex file. It is linked to an external dll and it worked fine (it returns correctly to matlab a vector). Recently I added an new function inside my c++ file which does not affect the result of the c++ function but is just used to improve some data manipulation. By the way, this function works quite well in a simple c++ file and I have already used many times in other c++ files (no-mex files).
> After added this function my matlab crashes and returns me this error:
>
>
> MATLAB crash file:C:\DOCUME~1\MILCEMEA~1.VAA\LOCALS~1\Temp\matlab_crash_dump.2996
> ------------------------------------------------------------------------
> Segmentation violation detected at Wed Jul 28 18:38:04 2010
> ------------------------------------------------------------------------
>
> Operating System: Microsoft Windows XP
> Window System: Version 5.1 (Build 2600: Service Pack 3)
> Processor ID: x86 Family 6 Model 7 Stepping 10, GenuineIntel
> Virtual Machine: Java 1.6.0_04-b12 with Sun Microsystems Inc. Java HotSpot(TM) Client VM mixed mode
> Default Encoding: windows-1252
>
> Fault Count: 1
>
> Register State:
> EAX = ffff5df8 EBX = 00c2e01c
> ECX = ffffffff EDX = e06d7363
> ESI = ffff5df4 EDI = 04f169ec
> EBP = 00c2e028 ESP = 00c2cf40
> EIP = 04ec186e FLG = 00010286
>
> Stack Trace:
> [0] qlDiscountFactors.mexw32:0x04ec186e(0x00c2e158 "x£", 0x00c2e0b8, 0x00c2e1fc, 0)
> [1] 0x00c2e20c(0x8b00032b, 0x04c483d8, 0x85e85d89, 0xb7840fdb)
>
> This error was detected while a MEX-file was running............
>
> Any suggestion???
> thanks in advance





I FORGOT THE CODE IN MY PAST EMAIL: (the function that crashes matlab is almost at the end of the code zcschedule().

---------------------------------------
#include "qlDiscountFactors.h"
#include <iostream>
#include <iomanip>
#include <ql/quantlib.hpp>
#include <ql/termstructures/yield/discountcurve.hpp>
#include <ql/math/interpolation.hpp>
#include <ql/indexes/iborindex.hpp>
#ifdef BOOST_MSVC
/* Uncomment the following lines to unmask floating-point
exceptions. Warning: unpredictable results can arise...
See http://www.wilmott.com/messageview.cfm?catid=10&threadid=9481
Is there anyone with a definitive word about this?
*/
//#include <float.h>
// namespace { unsigned int u = _controlfp(_EM_INEXACT, _MCW_EM); }
#endif
#include <boost/timer.hpp>
#include <iostream>
#include <iomanip>
#if defined(QL_ENABLE_SESSIONS)
namespace QuantLib {
Integer sessionId() { return 0; }
}
#endif

#pragma comment(lib, "libmx.lib")
#pragma comment(lib, "libmat.lib")
#pragma comment(lib, "libmex.lib")

using namespace std;
using namespace QuantLib;

std::vector<Date> genListOfDates(Date startdate,
Date enddate,
Period freq,
BusinessDayConvention rollconv,
Calendar cal)
{
std::vector<Date> listofdates;
listofdates.push_back(startdate);
Date tempdate=startdate;
while (tempdate <= enddate) {
Date newtempdate = cal.advance(tempdate,freq,rollconv,false);
listofdates.push_back(newtempdate);
tempdate = newtempdate;
}
return listofdates;
}

BusinessDayConvention getRollingConventionfromnum(int num)
{
switch(num)
{
case 1:
return Preceding;
break;
case 2:
return ModifiedPreceding;
break;
case 3:
return Following;
break;
case 4:
return ModifiedFollowing;
break;
}
}

TimeUnit getTimeUnitfromnum(int num)
{
switch(num)
{
case 1:
return Days;
break;
case 2:
return Weeks;
break;
case 3:
return Months;
break;
case 4:
return Years;
break;
}

}

Calendar createCalendarfromnum(int num)
{
switch(num)
{
case 1 :
return Argentina();
break;
case 2 :
return Australia();
break;
case 3:
return BespokeCalendar();
break;
case 4:
return Brazil();
break;
case 5:
return Canada();
break;
case 6:
return China();
break;
case 7:
return CzechRepublic();
break;
case 8:
return Denmark();
break;
case 9:
return Finland();
break;
case 10:
return Germany();
break;
case 11:
return HongKong();
break;
default:
throw("unknown calendar number");
}
}

DayCounter createDayCounterfromnum(int num)
{

switch(num)
{
case 1 :
return Actual365Fixed();
break;
case 2 :
return Actual360();
break;
case 3:
return Thirty360(Thirty360::USA);
break;
case 4:
return Thirty360(Thirty360::European);
break;
case 5:
return Thirty360(Thirty360::Italian);
break;
case 6:
return ActualActual(ActualActual::Bond);
break;
case 7:
return ActualActual(ActualActual::Euro);
break;
case 8:
return ActualActual(ActualActual::Historical);
break;
}
}

void mexFunction(int nlhs, mxArray *plhs[], int nrhs, mxArray *prhs[])
{
mxArray *inDates = prhs[0];
double nDates = mxGetScalar(prhs[1]);
mxArray *inInstruments = prhs[2];
double nInst = mxGetScalar(prhs[3]);
double dcf = mxGetScalar(prhs[4]);
double roll = mxGetScalar(prhs[5]);
double cal = mxGetScalar(prhs[6]);
double interp = mxGetScalar(prhs[7]);

plhs[0]=mxCreateDoubleMatrix(nDates-1,1,mxREAL);

qlDiscountFactors(mxGetPr(inDates), (int)nDates, mxGetPr(inInstruments) , (int)nInst, (int)dcf, (int)roll, (int)cal, (int) interp, mxGetPr(plhs[0]));

}

void qlDiscountFactors(double *refdate,
int nDates,
double *instruments,
int nInst,
int daycounter,
int rollconv,
int calnum,
int interp,
double *oDF)
{
try {

// Day counter constructor
DayCounter daycount;
daycount = createDayCounterfromnum(daycounter);

// Rolling convention constructo
BusinessDayConvention rollconvention;
rollconvention = getRollingConventionfromnum(rollconv);

// Calendar constructor
Calendar cal;
cal= createCalendarfromnum(calnum);

// Retrieve the reference date and settlement date
Date referencedate((int)refdate[0]);
std::vector<Date> settlementdates;
int i=0;
for (i=0; i<nDates-1; ++i) {
Date settdate((int)refdate[i+1]);
settlementdates.push_back(settdate);
}

// Deposit rate constructors
Rate deporates;

// Future price constructors
Real futprices;

// Swap rate constructors
Rate swrates;

// Zero coupon constructors
Real couponrates;
Real cleanprice = 100.0;
Real redemption = 100.0;

// Instruments collection
std::vector<boost::shared_ptr<RateHelper>> instrumentCollection;

// Instruments for yield curve bootstrapping
int typeofinst;
Integer numtenor;
TimeUnit tenor;
Natural fixingdays = 0;
Integer futmonths = 3;
Frequency swFixedLegFreq = Annual;
Frequency bondFreq = Annual;
BusinessDayConvention swFixedLegConv = Unadjusted;
DayCounter swFixedLegDc = Thirty360(Thirty360::European);
boost::shared_ptr<IborIndex> swFloatingLegIndex(new Euribor6M);
Settings::instance().evaluationDate() = referencedate;
for (i=8; i<nInst; i++) {
if ((instruments[i] + 0.5) >= ((int)instruments[i] + 1)) {
typeofinst = (int)instruments[i] + 1;
} else {
typeofinst = (int)instruments[i];
}
if (typeofinst == 1) { ............... if (typeofinst == 4) { // Bond instruments <--- couponrates = instruments[nInst+i];
boost::shared_ptr<SimpleQuote> bondquotes(new SimpleQuote(cleanprice));
if ((instruments[2*nInst+i] + 0.5) >= ((int)instruments[2*nInst+i] + 1)) {
numtenor = (int)instruments[2*nInst+i] + 1;
} else {
numtenor = (int)instruments[2*nInst+i];
}
if ((instruments[3*nInst+i] + 0.5) >= ((int)instruments[3*nInst+i] + 1)) {
tenor = getTimeUnitfromnum((int)instruments[3*nInst+i] + 1);
} else {
tenor = getTimeUnitfromnum((int)instruments[3*nInst+i]);
}
Date thismaturity = cal.advance(referencedate,numtenor*tenor);
Schedule zcschedule(referencedate,
thismaturity,
Period(bondFreq),
cal,
rollconvention,
rollconvention,
DateGeneration::Backward,
false);
boost::shared_ptr<FixedRateBondHelper> zcratehelper(new FixedRateBondHelper(Handle<Quote>(bondquotes),
0,
cleanprice,
zcschedule,
std::vector<Rate>(1,couponrates),
daycount,
rollconvention,
redemption,
referencedate));

instrumentCollection.push_back(zcratehelper);
}

} // end for

// Yield curve constructor
/* double tolerance = 1.0e-15;
boost::shared_ptr<YieldTermStructure> depoFutSwapTermStructure(new PiecewiseYieldCurve<Discount,LogLinear>(referencedate,
instrumentCollection,
daycount,
tolerance));
RelinkableHandle<YieldTermStructure> discountCurve;
discountCurve.linkTo(depoFutSwapTermStructure);
*/
// Interpolated discount factors
for (i=0; i<nDates-1; ++i) {
// DiscountFactor df = discountCurve->discount(settlementdates[i],true);
oDF[i] = 1.09;
}

} catch (std::exception& e) {
std::cerr << e.what() << std::endl;
} catch (...) {
std::cerr << "unknown error" << std::endl;
}

}
From: Jan Simon on
Dear Paolo,

> Any suggestion???
The new function, you have added, seems to have a bug. Use a debugger to locate it. If you can locate the error within less than 20 lines of code, it sometimes help to post the code here, because 40.000 eyes can see more than 2.

Did you expect a more detailed or specific answer? Then we'd need a more detailed and specific description of the problem.

Good luck, Jan
From: Paolo on
Hi Jan,

debugging the code this is the exception I got:

"Unhandled exception at 0x04ce3620 (qlDiscountFactors.mexw32) in MATLAB.exe: 0xC0000005: Access violation writing location 0xffff5df8."

and the line is this

void release() // nothrow
{
-----------> if( BOOST_INTERLOCKED_DECREMENT( &use_count_ ) == 0 )
{
dispose();
weak_release();
}
}

Thanks in advanvance,
Paolo

"Jan Simon" <matlab.THIS_YEAR(a)nMINUSsimon.de> wrote in message <i2pou1$cfm$1(a)fred.mathworks.com>...
> Dear Paolo,
>
> > Any suggestion???
> The new function, you have added, seems to have a bug. Use a debugger to locate it. If you can locate the error within less than 20 lines of code, it sometimes help to post the code here, because 40.000 eyes can see more than 2.
>
> Did you expect a more detailed or specific answer? Then we'd need a more detailed and specific description of the problem.
>
> Good luck, Jan
From: Jan Simon on
Dear Paolo,

we cannot run your code, because we do not have the libs you use.
The description of the error is not complete. We see the line, but cannot find the corresponding line in the code you've posted.

You have to inspect the values of the variables and pointers using the debugger. I do not expect that the newsgroup can solve such problems.

Kind regards, Jan