2014-11-29 2 views
1

Valgrind에서이 오류는 무엇을 의미합니까? 다른 게시물을 많이 보았지만 실제로 오류의 의미를 이해하지 못합니다. 드래곤 소멸자 함수에 문제가 있습니까?Valgrind의 크기가 8입니다. C++

==48500== Invalid read of size 8 
==48500== at 0x40AF66: Dragon::~Dragon() (in /u3/nsah/cs246/1149/a5/cc3k/cc3k/test) 
==48500== by 0x40AFDB: Dragon::~Dragon() (in /u3/nsah/cs246/1149/a5/cc3k/cc3k/test) 
==48500== by 0x406841: Floor::deleteAll() (in /u3/nsah/cs246/1149/a5/cc3k/cc3k/test) 
==48500== by 0x4022D8: Floor::~Floor() (in /u3/nsah/cs246/1149/a5/cc3k/cc3k/test) 
==48500== by 0x401EE1: main (in /u3/nsah/cs246/1149/a5/cc3k/cc3k/test) 
==48500== Address 0x5a1d130 is 0 bytes inside a block of size 40 free'd 
==48500== at 0x4C2A4BC: operator delete(void*) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so) 
==48500== by 0x40A7B3: Treasure::~Treasure() (in /u3/nsah/cs246/1149/a5/cc3k/cc3k/test) 
==48500== by 0x40671B: Floor::deleteAll() (in /u3/nsah/cs246/1149/a5/cc3k/cc3k/test) 
==48500== by 0x4022D8: Floor::~Floor() (in /u3/nsah/cs246/1149/a5/cc3k/cc3k/test) 
==48500== by 0x401EE1: main (in /u3/nsah/cs246/1149/a5/cc3k/cc3k/test) 

편집 : 이 내 드래곤 클래스는 모습입니다 같은 :

#include "dragon.h" 
#include <iostream> 
#include <cmath> 
#include <cstdlib> 

using namespace std; 

Dragon::Dragon(Item *hoard) { 
    // initalizes some variables 
    treasureHoard = hoard; 
} 

Dragon::~Dragon(){ 
    treasureHoard->deadDragon(); 
} 

// some functions 

편집 :

D *ptr=new D(); 
// some code … 
if (ptr->isDead()) { 
    delete ptr; 
    ptr = NULL; 
} 
// some code 

// at the end of the program: 
if (ptr) { // <<< is this causing the error? 
    delete ptr; 
    ptr = NULL; 
} 
+1

드래곤 클래스의 코드를 표시 :

여기 (간단한 스택 있지만) 문제를 복제하는 완벽한 프로그램입니다. 초기화되지 않은 메모리를 읽는 중입니다. – erenon

+0

링크 http://stackoverflow.com/a/22658693/2724703 –

답변

1

나는 valgrind 메시지는 매우 분명하다 생각 : 은 기본적으로 내 코드는 다음과 수행 :

==48500== Address 0x5a1d130 is 0 bytes inside a block of size 40 free'd 

"free'd"(C++에서 가장 가능성이있는`delete'd)의 데이터 블록이 있으며 여전히 액세스 중입니다. 좀 더 정확히 말하자면, 크기가 40으로 시작된 해제 된 메모리 블록의 시작 부분에있는 8 바이트의 한 단어가 읽혀지고 있습니다.

즉, 효과적으로 코드는 다음의 도덕적 동등하고 있습니다 (대략 무슨 일이 일어나고 명확하게, 유형, 회원 및 변수 이름은 코드에서 다를 수 있지만, 그건)

T* ptr = new T; // allocator memory of an object of size 40 
... 
delete ptr;   // release the memory 
... 
X value = ptr->start; // read the first word of the data 

struct foo { 
    double values[5]; 
}; 

int main() 
{ 
    foo* ptr = new foo(); 
    delete ptr; 
    double x = ptr->values[0]; 
    return x; 
} 
+0

에 나와있는 단계를 수행 할 수 있습니다. 포인터를 삭제하면 프로그램이 끝나기 전에 포인터가 있는지 확인하기 만하면됩니다. 오류의 원인이 있습니까? 나는 다른 시간에 삭제 된 포인터에 액세스하려고 시도하지 않는다고 확신한다. (내 주요 질문 수정) –

+0

포인터 자체를 읽는 것은 정의되지 않은 동작입니다. 포인터가 삭제되면이 값을 유지하는 포인터에만 할당 할 수 있습니다. 읽기는 valgrind가보고하는 것입니다. 뭔가 포인터가 가리키는 값을 읽는 중일 수 있습니다. 코드와 스택 추적을 보면 내가 파괴 한 객체가 이미 삭제되었다고 추측 할 수 있습니다. –