我无法确定Valgrind错误的确切原因:
==3868== Invalid read of size 2
==3868== at 0x100001F1F: Shrinker::Execute() (in ./proj4B)
==3868== by 0x1000029CD: Filter::Update() (in ./proj4B)
==3868== by 0x100001819: Image::Update() const (in ./proj4B)
==3868== by 0x10000299E: Filter::Update() (in ./proj4B)
==3868== by 0x100001819: Image::Update() const (in ./proj4B)
==3868== by 0x10000299E: Filter::Update() (in ./proj4B)
==3868== by 0x100001819: Image::Update() const (in ./proj4B)
==3868== by 0x10000299E: Filter::Update() (in ./proj4B)
==3868== by 0x100001819: Image::Update() const (in ./proj4B)
==3868== by 0x10000299E: Filter::Update() (in ./proj4B)
==3868== by 0x100001819: Image::Update() const (in ./proj4B)
==3868== by 0x10000299E: Filter::Update() (in ./proj4B)
==3868== Address 0x100c12040 is 0 bytes inside a block of size 7,201,152 free'd
==3868== at 0x10000D94F: free (in /usr/local/Cellar/valgrind/HEAD/lib/valgrind/vgpreload_memcheck-amd64-darwin.so)
==3868== by 0x100001BD5: PNMreader::Execute() (in ./proj4B)
==3868== by 0x100001954: Source::Update() (in ./proj4B)
==3868== by 0x100001819: Image::Update() const (in ./proj4B)
==3868== by 0x10000299E: Filter::Update() (in ./proj4B)
==3868== by 0x100001819: Image::Update() const (in ./proj4B)
==3868== by 0x10000299E: Filter::Update() (in ./proj4B)
==3868== by 0x100001819: Image::Update() const (in ./proj4B)
==3868== by 0x10000299E: Filter::Update() (in ./proj4B)
==3868== by 0x100001819: Image::Update() const (in ./proj4B)
==3868== by 0x10000299E: Filter::Update() (in ./proj4B)
==3868== by 0x100001819: Image::Update() const (in ./proj4B)
我认为这是由于我在Shrinker :: Execute()中的嵌套循环和/或它的析构函数:
void Shrinker::Execute() {
int inWidth = 0, inHeight = 0, maxVal = 255;
int halfWidth = 0, halfHeight = 0;
inWidth = img1->GetWidth();
inHeight = img1->GetHeight();
halfWidth = inWidth / 2;
halfHeight = inHeight / 2;
buffer = (Pixel *) malloc(sizeof(Pixel)*halfWidth*halfHeight);
int in = 0, out = 0;
for (int i = 0; i < halfHeight; i++) {
for (int j = 0; j < halfWidth; j++) {
in = i*2*inWidth+j*2;
out = i*halfWidth+j;
buffer[out] = img1->GetPixels()[in];
}
}
img.ResetSize(halfWidth, halfHeight);
img.SetMaxVal(maxVal);
img.SetPixels(buffer);
} // end Shrinker::Execute()
我试图对Shrinker中的嵌套循环和malloc进行每次小调整,但无济于事。它的析构函数释放缓冲区并将其设置为NULL。任何指导都将不胜感激。
答案 0 :(得分:0)
实际上,我并不知道您的代码的目的。但是,您可能在下面的代码中使用了错误的参数:
in = i*2*inWidth+j*2;
应该是:
in = i*2*halfwidth+j*2;
我想。
答案 1 :(得分:0)
我在这里猜测,但是因为它可以访问之前已经免费的块 - 正在破坏Shrinker::Execute
中分配的缓冲区 - 如果唯一免费的地方是你的析构函数那么你可能得到了一个由Shrinker
创建的坏(可能是临时的)副本 - 如果你从一个函数返回一个Shrinker对象就会发生这种情况。
您需要确保您已经阻止副本被创建或正确实现了复制构造函数和赋值运算符。