当我将对象添加到< vector>时的Segfault
我用两种不同的方式编写了代码片段:使用二维数组作为矩阵,并使用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;
}
没有找到相关结果
已邀请:
4 个回复
埠仙俊
祁澈盘哼颗
代替
并从中更改初始化对象
至
我整天都在编码,所以我犯了一些荒谬的错误。 谢谢你的帮助!
物崎巩
期差骇蓟
这看起来很奇怪,malloc返回一个(void)指针,而不是一个指向指针的指针,但它可以用于[] []数组。重新校对之后似乎没问题:p 同时使用类Img和另一个使用名为“file”的变量实例化的Image可能会有点令人困惑。 有些代码也缺失了(例如'p'是什么)但是看起来没问题。如果我是你,我会在这里和那里放一些printf()来缩小程序崩溃的位置。 我最好的选择是p(i,j)索引可能超出范围。 祝好运!