c++ - 当我向 <vector> 添加对象时出现段错误

标签 c++ boost vector ublas

我用两种不同的方式编写代码片段:使用二维数组作为矩阵,以及使用 boost::ublas::matrix。当我在第一种情况下将此对象添加到它时它正在工作,但在第二种情况下我遇到了段错误。我想使用第二种方式,所以如果有人知道我为什么会遇到段错误,我将不胜感激。

代码:

img.h

#include <Magick++.h>
#include <string>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/io.hpp>

using namespace boost::numeric::ublas;
using namespace std;
using namespace Magick;

class Img
{
    public:
        Img();
        Img(const string path2file);

        unsigned int width, height;
        string filename;
    private:
        typedef struct pix
        {
            Quantum R;
            Quantum G;
            Quantum B;
        } pix;

        matrix<pix> p;

        pix **pixels;
    string format;
};

img.cpp

Img::Img(const string path2file)
{
 Image file;
 unsigned int i, j;
 Color pixel;

 file.read(path2file);

 filename = path2file;
 width = file.size().width();
 height = file.size().height();

// begin of first way
 pixels = (pix**)malloc(sizeof(pix*)*height);
 for(i=0 ; i<height ; ++i)
  pixels[i] = (pix*)malloc(sizeof(pix)*width);

 for(i=0 ; i<height ; ++i)
 {
  for(j=0 ; j<width ; ++j)
  {
   pixel = file.pixelColor(j, i);

   pixels[i][j].R = pixel.redQuantum();
   pixels[i][j].G = pixel.greenQuantum();
   pixels[i][j].B = pixel.blueQuantum();
  }
 }
// end of first way

// begin of second way
 p.resize(height, width);
 for(i=0 ; i<height ; ++i)
 {
  for(j=0 ; j<width ; ++j)
  {
   pixel = file.pixelColor(j, i);

   p(i, j).R = pixel.redQuantum();
   p(i, j).G = pixel.greenQuantum();
   p(i, j).B = pixel.blueQuantum();
  }
 }*/
}
// end of second way

我很确定这段代码不是段错误的原因。 但是当我在主程序中使用它时,我遇到了段错误(仅适用于第二种方式,第一种方式有效):

main.cpp

#include <iostream>
#include <stdio.h>
#include "img.h"
#include <vector>

using namespace std;

int main(void)
{
 std::vector<Img> files;
 files.push_back(Img("files/mini.bmp"));
 return 0;
}

最佳答案

将程序加载到 gdb 并使其崩溃。在 gdb 控制台中键入 bt 或 backtrace,您将获得所有调用的堆栈帧,您可以看到导致段错误的原因。

关于c++ - 当我向 <vector> 添加对象时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4695941/

相关文章:

c++ - BlackBerry 10 中的弹出窗口

c++ - 如何定义 boost::any 运算符 ==

r - 合并数据框和命名向量

c++ - 向同一网络上的所有其他应用程序实例发送消息

c++ - 使用 boost 进行半无限积分

c++ - 继承自定义类的 std::vector::iterator?

variables - Gnuplot:二维矢量图的可变颜色(和线宽)

c++ - 如何每次只获取最新的家庭动态

c++ - wordexp 和带空格的字符串

c++ - sqlite 数据库保持锁定/不可访问