문제 설명
C++에서 메모리 삭제 (Deleting memory in c++)
동적 메모리 할당을 사용하여 코드를 다시 작성하려고 하며 무엇보다도 이 질문(및 답변)이 도움이 됩니다. 그래서 Johanes Shaub의 조언에 따라 제 2D 배열을 다음과 같이 선언했습니다.
double (*q_1_matrix)[TIME] = new double[SPACE][TIME];
이제 코드를 실행하면 모든 것이 제대로 작동하는 것 같습니다. 그러나 메모리 할당을 다시 해제하기 위해 다음 줄을 추가하면:
for(i = 0; i < SPACE; ++i) {
delete [] q_1_matrix[i];
}
delete [] q_1_matrix;
다음 경고가 표시됩니다. 삭제 배열 '*(q_1_matrix + ((sizetype)(((long unsigned int)i) * 800ul) ))' [기본적으로 활성화됨] delete [] q_1_matrix[i]; 이후에 분할 오류(코어 덤프됨)가 발생합니다.
내가 무엇을 잘못하고 있는지 아는 사람이 있습니까?
참조 솔루션
방법 1:
the new
call is actually creating 1 big chunk of memory. It is only indexed as a 2‑dimensional array. you can just call delete[] q_1_matrix;
(without the for loop).
방법 2:
The question you refer to restricts answers to using new
, but you almost certainly don't need new
.
It is far simpler to use the standard library; then, all your worries go away:
std::vector<std::vector<double>> myvec(SPACE, std::vector<double>(TIME));
And if you instead wrap a std::vector<double>(SPACE*TIME)
in a class that simulates 2D indexing, so much the better.
Anyway, if you really must manage memory yourself, recall that you're creating one big chunk of dynamic memory here (with the type and dimensions of a double[SPACE][TIME]
), so you must free it only once:
delete[] q_1_matrix;
(by Hunter、Shloim、Lightness Races in Orbit)