我有以下代码结构:
[code 1]
cout << some_string << endl
cout << some_string << endl
cout << some_string << endl
cout << some_string << endl
cout << some_string << endl
[code 2]
当我删除cout
语句时,代码2在给出cout
语句时给出不同的输出。这是一些内存泄漏的迹象吗?
具体示例来自OPENCV的stitching_detailed.cpp。我有以下代码:
// code 1 - edit added cameras initialization
vector<CameraParams> cameras(0);
HomographyBasedEstimator estimator;
theRNG().state = 0;
estimator(features, pairwise_matches, cameras);
for (size_t i = 0; i < cameras.size(); ++i)
{
theRNG().state = 0;
Mat R;
cameras[i].R.convertTo(R, CV_32F);
cameras[i].R = R;
LOGLN("Initial intrinsics #" << indices[i]+1 << ":\n" << cameras[i].K());
}
// cout statements
for (size_t i = 0; i < cameras.size(); ++i)
{
cout << cameras[i].aspect << endl;
cout << cameras[i].focal << endl;
cout << cameras[i].K() << endl;
cout << cameras[i].ppx << endl;
cout << cameras[i].ppy << endl;
cout << cameras[i].R << endl;
cout << cameras[i].t << endl;
}
// code 2
theRNG().state = 0;
Ptr<detail::BundleAdjusterBase> adjuster;
if (ba_cost_func == "reproj") adjuster = new detail::BundleAdjusterReproj();
else if (ba_cost_func == "ray") adjuster = new detail::BundleAdjusterRay();
else
{
cout << "Unknown bundle adjustment cost function: '" << ba_cost_func << "'.\n";
return -1;
}
theRNG().state = 0;
Mat_<uchar> refine_mask = Mat::zeros(3, 3, CV_8U);
if (ba_refine_mask[0] == 'x') refine_mask(0,0) = 1;
if (ba_refine_mask[1] == 'x') refine_mask(0,1) = 1;
if (ba_refine_mask[2] == 'x') refine_mask(0,2) = 1;
if (ba_refine_mask[3] == 'x') refine_mask(1,1) = 1;
if (ba_refine_mask[4] == 'x') refine_mask(1,2) = 1;
adjuster->setRefinementMask(refine_mask);
adjuster->setConfThresh(conf_thresh);
(*adjuster)(features, pairwise_matches, cameras);
如果我删除cout
语句,则相机[x] .focal为NaN。如果我保留cout
语句,则摄像机[x] .focal具有有效值。
我知道要付出的不是很多,但我在调试它的最后努力。任何帮助调试问题的人都表示赞赏。即使你知道一种标准的调试方式,请告诉我。
答案 0 :(得分:3)
如果通过删除看似无关的代码来暴露错误,那几乎总是在程序中某处出现未定义行为错误的迹象,这些错误一直处于休眠状态,直到程序内存布局发生变化为止略。
对于会导致此类错误的未定义行为,有多种选择。未初始化的指针,指向错误位置的指针,数组越界错误等等。
(你也可以从堆栈溢出中获得这种行为,但在这种情况下似乎不太可能。)