>  기사  >  백엔드 개발  >  Valgrind 또는 AddressSanitizer를 사용하여 C++에서 메모리 누수를 찾는 방법은 무엇입니까?

Valgrind 또는 AddressSanitizer를 사용하여 C++에서 메모리 누수를 찾는 방법은 무엇입니까?

WBOY
WBOY원래의
2024-06-02 21:23:00703검색

C++에서 메모리 누수를 찾으려면 Valgrind와 AddressSanitizer를 활용할 수 있습니다. Valgrind는 누출을 동적으로 감지하여 주소, 크기 및 호출 스택을 표시합니다. AddressSanitizer는 메모리 오류 및 누수를 감지하는 Clang 컴파일러 플러그인입니다. ASan 누출 검사를 활성화하려면 컴파일 시 --leak-check=full 옵션을 사용하세요. 그러면 프로그램 실행 후 누출이 보고됩니다.

如何使用 Valgrind 或 AddressSanitizer 查找 C++ 中的内存泄漏?

Valgrind 또는 AddressSanitizer를 사용하여 C++에서 메모리 누수를 찾는 방법

소개
메모리 누수는 C++와 같은 언어에서 흔히 발생하는 문제입니다. 이러한 누출을 감지하고 해결하려면 Valgrind 및 AddressSanitizer와 같은 도구를 사용할 수 있습니다.

Valgrind로 메모리 누수 찾기
Valgrind는 메모리 누수를 감지할 수 있는 동적 메모리 디버깅 도구입니다. Valgrind를 사용하려면:

valgrind ./my_program

Valgrind는 프로그램을 실행하고 감지된 메모리 누수를 보고합니다. 출력에는 유출된 주소, 크기 및 호출 스택이 표시됩니다.

Example
다음 C++ 코드 예제는 Valgrind가 메모리 누수를 감지하는 방법을 보여줍니다.

int* ptr = new int[10];
// ...
// 忘记释放 ptr

이 코드를 실행하고 Valgrind를 사용하면 다음 출력이 생성됩니다.

==8445== LeakSanitizer: detected memory leaks
==8445== Direct leak of 40 bytes in 1 object(s) allocated from:
    #0 0x49f2c0 in default_new_allocator_000000157013e0000000 ::operator() () (_libunwind.dylib:0x103d8e000)
    #1 0x41626f in create_array () in /tmp/a.out:10
    #2 0x415b2d in main () in /tmp/a.out:15

SUMMARY:
==8445== LEAK SUMMARY:
==8445==    definitely lost: 40 bytes in 1 object(s)

출력에서는 40바이트가 누수되었으며 주소 0x49f2c0에 위치한다는 것을 보여줍니다. .

AddressSanitizer로 메모리 누수 찾기
AddressSanitizer(ASan)는 메모리 누수를 포함한 메모리 오류를 감지할 수 있는 Clang 컴파일러 플러그인입니다. ASan을 사용하려면:

clang++ -fsanitize=address ...

ASan은 메모리 액세스 오류를 감지하고 오류가 발생하면 충돌 보고서를 생성합니다. 메모리 누수를 확인하려면 프로그램을 두 번 실행하세요.

./my_program # 第一次运行
./my_program --leak-check=full # 第二次运行,启用泄漏检查

두 번째 실행에서는 감지된 메모리 누수를 보고합니다.

Example
다음 C++ 코드 예제는 AddressSanitizer가 메모리 누수를 감지하는 방법을 보여줍니다.

int* ptr = new int[10];
// ...
// 忘记释放 ptr

ASan을 활성화한 상태에서 이 코드를 컴파일하고 실행하면 다음과 같은 출력이 생성됩니다.

==28847== ERROR: AddressSanitizer: detected memory leaks
    SUMMARY:
    ==28847== LeakSanitizer: 40 byte(s) leaked in 1 allocation(s).
    ==28847==
    0x7fdd1b000010  40 bytes in 1 block
      ==28847== LeakSanitizer:
      ==28847==  Direct leak of 40 bytes in 1 object(s) allocated from:
      ==28847==    #0 0x7fdd17a346c0 in __sanitizer::Allocator<std::__detail::__shared_count>::allocate(unsigned long) (_sanitizer.h:1195)
      ==28847==    #1 0x7fdd184d0f90 in void* std::__detail::__shared_count<unsigned int>::allocate() (_shared_count.h:128)
      ==28847==    #2 0x7fdd182de485 in void* std::__shared_ptr<int>::__clone() (_shared_ptr.h:256)
      ==28847==    #3 0x48b935 in create_array() (/tmp/a.out:10)
      ==28847==    #4 0x48b884 in main (/tmp/a.out:15)

출력에서는 40바이트가 누수되었음을 보여주며, 0x7fdd1b000010에 할당된 주소에 있습니다.

위 내용은 Valgrind 또는 AddressSanitizer를 사용하여 C++에서 메모리 누수를 찾는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.