我一直無法查明確切的原因我Valgrind的錯誤: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)
我想這是因爲我在收縮器嵌套循環::執行()和/或它的析構函數:
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()
我試圖盡一切小的調整我能想到的這兩個嵌套循環和收縮機malloc的,但無濟於事。它的析構函數釋放緩衝區並將其設置爲NULL。任何指導將不勝感激。
顯示'Pixel'的定義。 'malloc'不應該在C++中使用,因爲它實際上並不開始具有不平凡構造函數的對象的生命週期 –
如果您懷疑析構函數問題,那麼顯示析構函數 –
來自Filter :: Update的地方很有用?也許錯誤進入'ResetSize','SetMaxVal',或'SetPixels'或'GetPixels()',你沒有顯示這些代碼。例如,這可能是'GetPixels'中的緩衝區溢出。 –