malloc():内存损坏(快速)C++

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22512143/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 00:06:16  来源:igfitidea点击:

malloc(): memory corruption (fast) c++

c++memorymalloc

提问by ??????? ?????

I'm new with c++ and I'm trying to calculate the convex hull of a Point(x,y,z) set using C++.

我是 C++ 新手,我正在尝试使用C++.

I have called the following method in the main method:

我在主方法中调用了以下方法:

vector<Point> convexHull(Point Points[], int n) {
    vector<Point> v;
    // Find the bottommost Point
    int ymin = Points[0].getY();
    int min = 0;
    for (int i = 1; i < n; i++) {
        int y = Points[i].getY();

        // Pick the bottom-most or chose the left most Point in case of tie
        if ((y < ymin) || (ymin == y && Points[i].getX() < Points[min].getX()))
            ymin = Points[i].getY(), min = i;
    }
    // Place the bottom-most Point at first position
    Points[min] = Points[0].swap(Points[min]);

    // Sort n-1 Points with respect to the first Point. A Point p1 comes
    // before p2 in sorted ouput if p2 has larger polar angle (in 
    // counterclockwise direction) than p1
    p0 = Points[0];
    qsort(&Points[1], n - 1, sizeof (Point), compare);

    // Create an empty stack and push first three Points to it.
    stack<Point> S; //  on debug the project I find that the problem is here 
    S.push(Points[0]);
    S.push(Points[1]);
    S.push(Points[2]);

    // Process remaining n-3 Points
    for (int i = 3; i < n; i++) {
        // Keep removing top while the angle formed by Points next-to-top, 
        // top, and Points[i] makes a non-left turn
        while (orientation(nextToTop(S), S.top(), Points[i]) != 2)
            S.pop();

        S.push(Points[i]);
    }

    // Now stack has the output Points, print contents of stack
    while (!S.empty()) {
        Point p = S.top();
        cout << "(" << p.getX() << ", " << p.getY() << ", " << p.getZ() << ")" << endl;
        v.push_back(Point(p.getX(), p.getY(), 0));
        S.pop();
    }
    return v;
}

It give this error:

它给出了这个错误:

*** glibc detected *** /home/user/NetBeansProjects/DGILOG-ask/dist/Debug/GNU-Linux-x86/dgilog-task: malloc(): memory corruption (fast): 0x08de1238 ***

I have searched in the web for the same error but I don't have understand what should I do.

我在网上搜索了同样的错误,但我不明白我该怎么办。

Point.cpp

点.cpp

#include <iostream>
#include <math.h>
#include <ostream>

using namespace std;

#include "Point.h"

Point::Point() : x(0), y(0), z(0) {
}

Point::Point(ostream &strm) {
    strm << "Type the abscissa: ", cin >> this->x;
    strm << "Type the ordinate: ", cin >> this->y;
    strm << "Type the applicate: ", cin >> this->z;
}

Point::Point(float x, float y, float z) : x(x), y(y), z(z) {
}

/**
 * Destructor
 */
Point::~Point() {
}

//Other methods

float Point::dist2D(Point &other) {
    float xd = x - other.x;
    float yd = y - other.y;
    return sqrt(xd * xd + yd * yd);
}

float Point::dist3D(Point &other) {
    float xd = x - other.x;
    float yd = y - other.y;
    float zd = z - other.z;
    return sqrt(xd * xd + yd * yd + zd * zd);
}

Point Point::swap(Point p) {
    Point aux(x, y, z);
    x = p.x;
    y = p.y;
    z = p.z;
    return aux;
}

void Point::print(ostream &strm) {
    strm << "Point(" << this->x << "," << this->y << "," << this->z << ")" << endl;
}

bool Point::operator<(const Point &p) const {
    return x < p.x || (x == p.x && y < p.y);
}

Thanks.

谢谢。

回答by PaulMcKenzie

Since you didn't post a complete program, here are some things you should look out for:

由于您没有发布完整的程序,因此您应该注意以下几点:

convexHull(Point Points[], int n)

convexHull(Point Points[], int n)

Nowhere in that function do you check if n is within bounds of the Points array. You should be using vector throughout your function. For example:

在该函数中没有任何地方检查 n 是否在 Points 数组的范围内。您应该在整个函数中使用向量。例如:

 int ymin = Points[0].getY();
 int min = 0;
 for (int i = 1; i < n; i++) {
    int y = Points[i].getY();

If I pass a NULL pointer as the first argument (or even an invalid pointer), or if n is too large, you have an access violation. Using vectors greatly reduces or outright removes these issues. With vector, you have the size() member function to do sanity tests to ensure that Point has the relevant number of entries. Right now, there is no way to do such tests in your function.

如果我将 NULL 指针作为第一个参数(甚至是无效指针)传递,或者如果 n 太大,则存在访问冲突。使用向量可以大大减少或彻底消除这些问题。使用 vector,您可以使用 size() 成员函数进行健全性测试,以确保 Point 具有相关数量的条目。目前,无法在您的函数中进行此类测试。

Next issue:

下一期:

S.push(Points[0]);
S.push(Points[1]);
S.push(Points[2]);

How do you know there are at least 3 entries in point? You don't know, and there is no way in that function to check. All you have is a pointer being passed, and some arbitrary number n. If you're using C++, you should not be in the habit of deliberately coding in a 'C'-like style. You have vector, so use it to its advantage.

你怎么知道至少有 3 个条目?您不知道,并且该函数无法进行检查。您所拥有的只是一个正在传递的指针和一些任意数字 n。如果您使用 C++,则不应养成刻意以类似“C”的风格进行编码的习惯。你有矢量,所以利用它的优势。

Next issue:

下一期:

qsort(&Points[1], n - 1, sizeof (Point), compare);

Since you didn't post what Point is, this usage of qsort() leads to undefined behavior if Points is a non-POD type.

由于您没有发布 Point 是什么,如果 Points 是非 POD 类型,则 qsort() 的这种用法会导致未定义的行为。

Stop using qsort(). Usage of qsort() within a C++ program is an indication that the coder is either 1) a C programmer who is using what they're used to (with the surprising unexpected reuslts that usually follow) or 2) A newbie C++ programmer who is reading C books or programs as a guidance in writing proper C++ programs.

停止使用 qsort()。在 C++ 程序中使用 qsort() 表明编码器是 1) 使用他们习惯的 C 程序员(通常会出现令人惊讶的意外结果)或 2) 新手 C++ 程序员阅读 C 书籍或程序作为编写正确 C++ 程序的指导。

Use std::sort() -- you're writing a C++ app, not a C application. The std::sort is typesafe, easier to use and setup, and works for POD and non-POD types that follow a strict-weak-ordering.

使用 std::sort() —— 您正在编写 C++ 应用程序,而不是 C 应用程序。std::sort 是类型安全的,更易于使用和设置,适用于遵循严格弱排序的 POD 和非 POD 类型。

回答by Claudiordgz

By the look of the error, and the place you are saying it crashes (a declaration), it very well may be in the qsort function. It is the only C library call you have in the code, and the error can't be in the declaration of the stack since it is just a declaration.

从错误的外观以及您说它崩溃的地方(声明)来看,它很可能在 qsort 函数中。它是代码中唯一的 C 库调用,错误不能出现在堆栈的声明中,因为它只是一个声明。

The first thing you should do is check bounds

你应该做的第一件事是检查边界

vector<Point> convexHull(Point Points[], int n) {
  vector<Point> v;
  if(n <= 3){ 
     // error
  }else{
    //the chunk of code
  } 
  return v;
}

But wait... there's more, suppose you want to replace the Points array with a vector

但是等等...还有更多,假设您想用向量替换 Points 数组

std::vector<Point> convexHull(vector<Point>::iterator begin, vector<Point>::iterator end) {
  std::vector<Point> returnVal;
  if(n <= 3){ 

  }else{
    //the chunk of code
  } 
  return returnVal;
}
// just don't forget to check your returnVal for empty size, error handling is a must

Or you could just use your c style old school method with a vector... which i don't recommend because you stop learning about iterators, which you should.

或者你可以只使用带有向量的 c 风格老派方​​法......我不推荐这样做,因为你停止学习迭代器,你应该这样做。

vector<Point> Points(100);
vector<Point> v;
if(convexHull(&Points[0], Points.size())) ///< how would you be testing this
{
   //yay
}

Oh, and by the way, implementing std::sort is really easy, don't be afraid, it is like this

哦,顺便说一句,实现 std::sort 真的很简单,别怕,是这样的

std::sort (&Points[1], &Points[1]+ (n-1));

Which would be easier if Points where iterators

如果 Points where iterators 会更容易

std::sort (begin+1, end);

You could even go further and use std::advance, which you should

你甚至可以更进一步使用 std::advance,你应该这样做

vector<Point>::iterator it = begin;   
std::advance(it,1);
std::sort (it, end);

So in conclusion how would the first part look with iterators?

那么总而言之,第一部分如何使用迭代器?

std::vector<Point> convexHull(vector<Point>::iterator begin, vector<Point>::iterator end)
{
  vector<Point> v;
  // Find the bottommost Point
  int ymin = begin->getY();
  vector<Point>::iterator l_it = begin; 
  vector<Point>::iterator min_position = begin;
  std::advance(l_it, 1);
  for (; l_it != end; ++l_it) 
  {
      int y = l_it->getY();

      // Pick the bottom-most or chose the left most Point in case of tie
      if ((y < ymin) || (ymin == y && l_it->getX() < min_position->getX()))
      {
          ymin = l_it->getY();
          min_position = l_it;
      }
   /// MORE CODE
}