2014-03-31 1 views
1

이 경우 메모리를 올바르게 해제하는 방법은 무엇입니까?이 경우 메모리를 올바르게 해제하는 방법

int n=0; 
cin >> n; 
float* matrix; 

matrix = new float [ n * 3 ]; 

for(int i = 0; i < n; i++) { 
    for(int j = 0; j < 3; j++) { 
     cin >> *(matrix + i * 3 + j); 
    } 
} 

int* array_of_numbers_of_circles = findIntersection(matrix,n); 

for(int i = 0; i < n; i++) { 
    for(int j = 0; j < 2; j++) { 
     if(*(array_of_numbers_of_circles + i * 2 + j) != 0) { //it writes error in if; 
      cout << *(array_of_numbers_of_circles + i * 2 + j) << " "; 
     } 
    } 
    if(*(array_of_numbers_of_circles + i * 2 + 0) != 0 && 

    *(array_of_numbers_of_circles + i * 2 + 1) != 0) { //it writes error in if here too; 
     cout << "\n"; 
    } 
} 

delete[] matrix; 
delete[] array_of_numbers_of_circles; 

:

이 주요 기능이다

"조건부 점프 또는 이동은 초기화되지 않은 값 (들)에 따라 달라집니다"Valgrind의가하는 이유를 이해가 안

내가 가진 것을 쓴다 기능 :

int* findIntersection(float matrix[], int n) { 
//some variables 

int* array_of_numbers_of_circles; 

array_of_numbers_of_circles = new int [ n * 2 ]; 

for(int i = 0; i < n; i++) { 
    for(int j = i + 1; j < n; j++) { 
     //some code here 


     *(array_of_numbers_of_circles + i * 2 + 0) = i + 1; 
     *(array_of_numbers_of_circles + i * 2 + 1) = j + 1; 

    } 
} 

return array_of_numbers_of_circles; 

} 

무엇이 문제입니까? VALGRIND가 그런 오류를 말하는 이유를 모르겠다.

감사합니다!

+0

메모리를 자동으로 삭제하고 버퍼 오버런을 확인하려면 std :: vector를 사용하십시오. –

+0

"some code here"에 'continue'또는 'break'문이 포함되어 있지 않습니까? 내 요점은 - array_of_numbers_of_circles의 _all_ 요소가 _really_initialized인지 100 % 확실한가요? 디버거를 사용하여이를 확인할 수도 있습니다. –

+1

좀 더 일반적이고 간단한'matrix [i * 3 + j] 대신'* (matrix + i * 3 + j)'를 사용하는 이유는 무엇입니까? – HEKTO

답변

5

먼저 "조건부 점프 또는 이동은 초기화되지 않은 값에 따라 달라집니다"라는 경고는 메모리를 올바르게 해제했는지 여부와 아무 관련이 없습니다.

array_of_numbers_of_circles의 모든 요소를 ​​초기화하지 않습니다.

외부 루프에 i == n-1이 있으면 내부 루프가 0 번 실행됩니다. 따라서 인덱스 2 * n - 22 * n - 1의 요소는 초기화되지 않습니다. 그러나 main의 줄에 사용됩니다. if(*(array_of_numbers_of_circles + i * 2 + j) != 0)

//some code here의 내용에 따라 초기화되지 않은 배열의 다른 요소가있을 수 있습니다.

+0

// 여기에있는 일부 코드는 스턴트를 확인하는 코드 행을 의미하며 올바르게 수행되면 * (array_of_numbers_of_circles + i * 2 + 0) = i + 1; * (array_of_numbers_of_circles + i * 2 + 1) = j + 1; –

1

오류 메시지 종류에서 알 수 있듯이 Valgrind에서는 값을 초기화하기 전에 값을 사용하고 있다고 생각하기 때문에 이러한 현상이 발생할 수 있습니다. Valgrind 플래그를 사용하여 초기화되지 않은 값의 출처를 알려줍니다.

원래 질문에 대한 답변 : "이 경우 메모리를 올바르게 확보하는 방법" 코드를 사용하면 코드를 더욱 안정적이고 강력하게 만들기 위해 std::vectorstd::auto_ptr으로 전환하는 것이 좋습니다.

+0

+1.사람들이 왜 그렇게 할 필요없이 C 스타일로 포인터를 던지라고 주장하는지 이해할 수 없습니다. – DevSolar