hi! find and fix error "std::vector<>::operator=(), std::throw_bad_alloc()" in code "void TkNimbleComponent::postprocess(std::vectorcv::Mat &batchedImage)
{
auto t0 = nutils::time();
std::vector cropArea = {0.0, 0.0, 1.0, 1.0};
auto dets = this->tkNimbleDetector->getDetections();
assert(dets.size() == batchedImage.size());
if (this->toCalculateDistances)
{
assert(dets.size() == cameraParams_.size());
}
code
for (size_t i = 0; i < dets.size(); ++i)
{
if (this->toCalculateDistances_)
{
cropArea = this->cameraParams_[i].roi;
}
std::vector<cv::Point> tlBrCoords(2);
tlBrCoords = this->tkNimbleDetector_->getTlBrCrops(cropArea, batchedImage[i]);
cv::Point tl = tlBrCoords[0];
cv::Point br = tlBrCoords[1];
auto it = dets[i].begin();
while(it != dets[i].end())
{
// Filtering bounding boxes
// 1. Remove objects which IDs don't present in classes.names or dimensions are zero or negative
if ((!classesDescr_[(*it).cl].toSend) || ((*it).w <= 0 || (*it).h <= 0) )
{
// Due to deletion in loop, iterator became
// invalidated. So reset the iterator to next item.
it = dets[i].erase(it);
}
// 2. If crop area is defined, remove bboxes, which are outside of it
else if (!(cropArea == std::vector<float>{0, 0, 1, 1}))
{
if ( (((*it).x <= tl.x &&
((*it).x + (*it).w) <= tl.x ) ||
((*it).x >= br.x &&
((*it).x + (*it).w) >= br.x )) ||
(((*it).y <= tl.y &&
((*it).y + (*it).h) <= tl.y ) ||
((*it).y >= br.y &&
((*it).y + (*it).h) >= br.y ))
)
{
it = dets[i].erase(it);
}
else
{
it++;
}
}
// 3. If bbox exceeds the image boundaries, crop it by these boundaries
else
{
(*it).x = std::max<float>((*it).x, 0);
(*it).y = std::max<float>((*it).y, 0);
if (static_cast<int>((*it).x + (*it).w) > batchedImage[i].cols)
{
(*it).w = static_cast<float>(batchedImage[i].cols - static_cast<int>((*it).x));
}
if (static_cast<int>((*it).y + (*it).h) > batchedImage[i].rows)
{
(*it).h = static_cast<float>(batchedImage[i].rows - static_cast<int>((*it).y));
}
it++;
}
}
// Draw detection region of interest
if (this->toDrawCropArea_)
{
cv::rectangle(batchedImage[i], cv::Rect(tl, br), cv::Scalar(0, 255, 0), 2);
}
}
this->tkNimbleDetector_->setDetections(dets); // update detections after filtering
// Draw bounding boxes
if (!this->drawnObjectPubs_.empty())
{
tkNimbleDetector_->drawDetections(batchedImage);
}
auto t1 = nutils::time();
if (this->toShowDebugTime_)
{
std::cout << " postproc: " + std::to_string(t1-t0) << std::endl;
}
}
"
The error "std::vector<>::operator=(), std::__throw_bad_alloc()" indicates a std::bad_alloc exception being thrown during a vector assignment operation, which usually means the system is running out of memory or the vector is being assigned an unexpectedly large size.
Here you create a vector tlBrCoords with 2 elements, then immediately assign it to the result of getTlBrCrops, possibly resizing it.
Possible causes:
getTlBrCrops returns a very large or invalid vector
If the getTlBrCrops function returns a large vector or a corrupted vector, then the assignment tlBrCoords = ... could trigger the bad_alloc. You should inspect or add bounds checks inside getTlBrCrops.
Unexpected large allocations elsewhere
The vector could become huge if the data processed is unexpectedly big or uninitialized.
Infinite or invalid recursion or logic error
The method getTlBrCrops or any other in the chain could be creating vectors that grow uncontrollably.
Fixes and recommendations:
1. Avoid unnecessary pre-sizing and directly assign:
You don't need to pre-size tlBrCoords before assignment:
cpp
// Remove the pre-sizing
std::vector<cv::Point> tlBrCoords = this->tkNimbleDetector_->getTlBrCrops(cropArea, batchedImage[i]);
This change prevents potential double allocations but normally should not cause bad_alloc unless the returned vector is huge.
2. Debug the output of getTlBrCrops:
Add checks after getting tlBrCoords to verify it has expected number of points (at least 2):
cpp
auto tlBrCoords = this->tkNimbleDetector_->getTlBrCrops(cropArea, batchedImage[i]);
if (tlBrCoords.size() < 2)
{
throw std::runtime_error("getTlBrCrops returned fewer than 2 points");
}
cv::Point tl = tlBrCoords[0];
cv::Point br = tlBrCoords[1];
If this throws, your crop calculation is broken — you should fix getTlBrCrops.
3. Check memory usage and input validity:
Is batchedImage[i] always valid and contains reasonable data?
Are cropArea values correct and not producing invalid crop rectangle sizes?
4. (If possible) Use try-catch for debugging:
Surround your assignment with try-catch to confirm exception source:
auto tlBrCoords = this->tkNimbleDetector_->getTlBrCrops(cropArea, batchedImage[i]);
if (tlBrCoords.size() < 2)
{
throw std::runtime_error("getTlBrCrops returned fewer than 2 points");
}
cv::Point tl = tlBrCoords[0];
cv::Point br = tlBrCoords[1];
Then verify the implementation and behavior of getTlBrCrops.
If after these changes, the error persists, please check or share the implementation of getTlBrCrops, as it is likely the root cause of the bad allocation.
Thanks for sharing the implementation of getTlBrCrops. It looks straightforward and returns exactly two points (top-left and bottom-right) calculated from the normalized cropArea and the image size.
Given that this function always returns a vector with exactly two elements, the cause of the std::bad_alloc error is unlikely to stem directly from this function.
What else could cause the problem?
Uninitialized or invalid cropArea vector
If cropArea has fewer than 4 elements, indexing cropArea[0] .. cropArea[3] causes undefined behavior.
This can cause memory corruption and potentially lead to bad_alloc later.
Very large values in cropArea or img.cols/img.rows
If img.cols or img.rows are very large (say, an invalid or huge image), then xTl, xBr etc. could be large values that trigger unexpected behavior later in the code.
batchedImage[i] being invalid or corrupted
If the image is invalid or has strange dimensions, that might cause problems elsewhere.
Iterator invalidation or complex reallocation during erase operations in your loop
You are modifying dets[i] (which seems to be a vector or similar container) while iterating. Make sure this container supports safe erase during iteration as your code logic assumes.
If the container is extremely large, repeated filtering can cause large memory allocations.
Actions & fixes:
1. Validate cropArea before using
Add an assertion or exception to check its size:
cpp
if (cropArea.size() < 4) {
throw std::invalid_argument("cropArea must have at least 4 elements");
}
Insert this either inside postprocess() or inside getTlBrCrops().
2. Validate img size before using
You can check inside postprocess or at the start of getTlBrCrops:
cpp
if (img.empty()) {
throw std::invalid_argument("Input image is empty");
}