Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 

new/delete의 짝이 맞는 경우에도 메모리 누수가 발생한다면?

PDB 심볼을 다루다보면 ISymUnmanagedMethod 인터페이스의 GetSequencePoints 메서드를 이용해 ISymUnmanagedDocument 배열을 반환받는 과정이 다음과 같이 펼쳐집니다.

netmf /client_v4_2_comm/CLR/Tools/Parser/Support.cpp
; https://searchcode.com/codesearch/view/11140450/

pOffsets  = new ULONG32[cSeqPoints]; // 배열 할당
// ...[생략]...
pDocs     = new ISymUnmanagedDocument*[cSeqPoints]; // 배열 할당

// GetSequencePoints 메서드에서 cSeqPoints 개수만큼 할당된 배열에 내용이 채워짐
TINYCLR_CHECK_HRESULT(pMethod->GetSequencePoints( cSeqPoints, &cSeqPoints, pOffsets, pDocs, pLines, pCols, pEndLines, pEndCols ));

for(ULONG32 i = 0; i < cSeqPoints; i++)
{
    if(i == cSeqPoints || ipOffset < pOffsets[i+1])
    {
        // ...[생략]...
    }
}

// ...[생략해서는 안되는 코드, 그런데 저는 생략했음!]...

delete[] pOffsets; // 배열 할당 해제
// ...[생략]...
delete[] pDocs; // 배열 할당 해제

(위의 코드를 알고 그대로 사용했다면 실수를 안했을 텐데!) 제 나름대로 ISymUnmanagedMethod 인터페이스 사용방법을 터득해 나가다가 저렇게 "...[생략해서는 안되는 코드]..." 영역을 생략해 버리고 작성하게 되는 실수를 했습니다.

그야말로 무심코! 배열 할당을 했으니 그냥 할당된 배열만 짝을 맞춰 해제시키기만 했고 하루 정도의 응용 프로그램 부하 테스트에서 여지없이 Memory Leak이 발생한 것입니다.

사실, 나름대로 완벽하게 new/delete를 맞췄기 때문에 처음에는 '참 희한하다...' 라고 생각했는데. ^^

알고 보니, 배열이 포함한 요소의 타입이 인터페이스인 경우 그것까지도 명백하게 해제를 해야 Memory Leak이 안 났습니다. 즉, "...[생략해서는 안되는 코드]..."가 이렇게 존재해야만 합니다.

if(pDocs)
{
    for(ULONG32 i = 0; i < cSeqPoints; i++)
    {
        if(pDocs[i])
        {
            pDocs[i]->Release();
        }
    }
}

외부에서 얻어온 인터페이스는 철저하게 해제를 해줘야 한다는 상식!... 을 어느새 잊어버린 것입니다. ^^




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 7/10/2021]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... 76  77  78  79  80  81  82  83  [84]  85  86  87  88  89  90  ...
NoWriterDateCnt.TitleFile(s)
11836정성태3/5/201923363오류 유형: 525. Visual Studio 2019 Preview 4/RC - C# 8.0 Missing compiler required member 'System.Range..ctor' [1]
11835정성태3/5/201921843.NET Framework: 810. C# 8.0의 Index/Range 연산자를 .NET Framework에서 사용하는 방법 및 비동기 스트림의 컴파일 방법 [3]파일 다운로드1
11834정성태3/4/201920639개발 환경 구성: 432. Visual Studio 없이 최신 C# (8.0) 컴파일러를 사용하는 방법
11833정성태3/4/201921195개발 환경 구성: 431. Visual Studio 2019 - CMake를 이용한 공유/실행(so/out) 리눅스 프로젝트 설정파일 다운로드1
11832정성태3/4/201917106오류 유형: 524. Visual Studio CMake - rsync: connection unexpectedly closed
11831정성태3/4/201916935오류 유형: 523. Visual Studio 2019 - 새 창으로 뜬 윈도우를 닫을 때 비정상 종료
11830정성태2/26/201916627오류 유형: 522. 이벤트 로그 - Error opening event log file State. Log will not be processed. Return code from OpenEventLog is 87.
11829정성태2/26/201918323개발 환경 구성: 430. 마이크로소프트의 CoreCLR 프로파일러 예제 빌드 방법 - 리눅스 환경 [1]
11828정성태2/26/201926223개발 환경 구성: 429. Component Services 관리자의 RuntimeBroker 설정이 2개 있는 경우 [8]
11827정성태2/26/201919153오류 유형: 521. Visual Studio - Could not start the 'rsync' command on the remote host, please install it using your system package manager.
11826정성태2/26/201919341오류 유형: 520. 우분투에 .NET Core SDK 설치 시 패키지 의존성 오류
11825정성태2/25/201924606개발 환경 구성: 428. Visual Studio 2019 - CMake를 이용한 리눅스 빌드 환경 설정 [1]
11824정성태2/25/201919046오류 유형: 519. The SNMP Service encountered an error while accessing the registry key SYSTEM\CurrentControlSet\Services\SNMP\Parameters\TrapConfiguration. [1]
11823정성태2/21/201920650오류 유형: 518. IIS 관리 콘솔이 뜨지 않는 문제
11822정성태2/20/201918993오류 유형: 517. docker에 설치한 MongoDB 서버로 연결이 안 되는 경우
11821정성태2/20/201919743오류 유형: 516. Visual Studio 2019 - This extension uses deprecated APIs and is at risk of not functioning in a future VS update. [1]
11820정성태2/20/201922820오류 유형: 515. 윈도우 10 1809 업데이트 후 "User Profiles Service" 1534 경고 발생
11819정성태2/20/201922079Windows: 158. 컴퓨터와 사용자의 SID(security identifier) 확인 방법
11818정성태2/20/201920168VS.NET IDE: 131. Visual Studio 2019 Preview의 닷넷 프로젝트 빌드가 20초 이상 걸리는 경우 [2]
11817정성태2/17/201916522오류 유형: 514. WinDbg Preview 실행 오류 - Error : DbgX.dll : WindowsDebugger.WindowsDebuggerException: Could not load dbgeng.dll
11816정성태2/17/201919986Windows: 157. 윈도우 스토어 앱(Microsoft Store App)을 명령행에서 직접 실행하는 방법
11815정성태2/14/201918201오류 유형: 513. Visual Studio 2019 - VSIX 설치 시 "The extension cannot be installed to this product due to prerequisites that cannot be resolved." 오류 발생
11814정성태2/12/201917070오류 유형: 512. VM(가상 머신)의 NT 서비스들이 자동 시작되지 않는 문제
11813정성태2/12/201918365.NET Framework: 809. C# - ("Save File Dialog" 등의) 대화 창에 확장 속성을 보이는 방법
11812정성태2/11/201915698오류 유형: 511. Windows Server 2003 VM 부팅 후 로그인 시점에 0xC0000005 BSOD 발생
11811정성태2/11/201920933오류 유형: 510. 서버 운영체제에 NVIDIA GeForce Experience 실행 시 wlanapi.dll 누락 문제
... 76  77  78  79  80  81  82  83  [84]  85  86  87  88  89  90  ...