0

我以两种不同的方式编写代码:使用二维数组作为矩阵,以及使用 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

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

主文件

#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;
}
4

4 回答 4

2

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

于 2011-01-14T21:12:59.803 回答
1

问题在我写的定义中。应该:

vector<Img*> files;

代替

vector<Img> files;

并更改初始化对象

Img tmp("path_to_file");

Img* tmp = new Img("path_to_file");

我已经厌倦了一整天的编码,所以我犯了一些荒谬的错误。

谢谢你的帮助!

于 2011-01-14T22:30:59.133 回答
0

在valgrind下运行您的程序,它将帮助您找到段错误的原因和位置。

于 2011-01-14T21:33:37.997 回答
0
pixels = (pix**)malloc(sizeof(pix*)*height);

这看起来很奇怪, malloc 返回一个(void)指针,而不是指向指针的指针,但我猜它可以用于 [][] 数组。重新校对后似乎没问题:p

同时拥有一个类 Img 和另一个使用名为 'file' 的变量实例化的 Image 可能有点令人困惑。

一些代码也丢失了(例如“p”是什么),但那里的代码似乎还可以。如果我是你,我会在这里和那里放一些 printf() 来缩小程序崩溃的范围。我最好的选择是 p(i,j) 索引可能超出范围。

祝你好运!

于 2011-01-14T21:55:28.723 回答