C++에서 메모리 삭제 (Deleting memory in c++)


문제 설명

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 HunterShloimLightness Races in Orbit)

참조 문서

  1. Deleting memory in c++ (CC BY‑SA 2.5/3.0/4.0)

#C++ #arrays #memory






관련 질문

파일의 암호화/복호화? (Encryption/ Decryption of a file?)

이상한 범위 확인 연산자가 있는 C++ typedef (C++ typedef with strange scope resolution operator)

개체 배열 매개변수--오류: '문자' 필드에 불완전한 유형이 있습니다. (Object array parameter--error: field ‘letters’ has incomplete type)

C++에서 메모리 삭제 (Deleting memory in c++)

C++ 프로그램을 실행할 수 없습니다. No se ejecuta el programa (C++ i can't run a program. No se ejecuta el programa)

컴파일 시 변수의 이름과 수명 (Name and lifetime of variables at compile time)

control-c 후 Visual Studio 콘솔 프로그램 충돌 (visual studio console program crashes after control-c)

멤버 변수에 std::enable_if 또는 유사한 메서드 사용 (Using std::enable_if or similar method on member variable)

ifstream input_file(filename); (I am receiving an error "no matching function to call" in the line ifstream input_file(filename);)

ESP8266에서 잠시 실행하면 JsonData 크기가 0이 됩니다. (JsonData size becomes zero after awhile of running in ESP8266)

합에 대한 속도 문제(제수의 합) (Speed problem for summation (sum of divisors))

벡터 벡터에서 하위 벡터의 첫 번째 값을 찾기 위해 begin() 및 end() 반복기의 범위를 지정하는 방법은 무엇입니까? (How to specify a range for begin() and end() iterators to find first value of sub vector in a vector of vectors?)







코멘트