C 및 C++에서 초기화되지 않은 메모리는 안정성 문제, 메모리 안전 버그, 정보 유출의 흔한 원인이 됩니다. 이러한 문제를 방지하기 위해 Android에서는 최대한 많은 메모리를 초기화합니다.
0으로 초기화된 사용자 공간 메모리
Android 12부터 스택 메모리는 모든 플랫폼 네이티브 코드(JNI 포함)에서 0으로 초기화되고 힙 메모리는 모든 플랫폼 네이티브 프로세스(예: netd)에서 0으로 초기화되지만 zygote 또는 앱에서는 0으로 초기화되지 않습니다.
NDK로 빌드된 퍼스트 파티 및 서드 파티 앱에서는 -ftrivial-auto-var-init=zero컴파일러 플래그를 사용하여 스택 로컬 변수를 0으로 초기화하는 것이 좋습니다. 불필요한 0은 모두 컴파일러가 최적화합니다.
예를 들어 로컬 변수가 명시적으로 초기화되는 경우입니다(예: int x = 123; 변수 x는 한 번만 초기화됨).
프로그램의 성능 핫스팟에 큰 스택 버퍼가 있는 경우 개발자는 컴파일러 속성을 사용하여 초기화를 사용 중지할 수 있습니다.
스택 초기화의 경우 GKI는 CONFIG_INIT_STACK_ALL_ZERO 구성을 사용하므로 -ftrivial-auto-var-init=zero 컴파일러 플래그를 사용하여 커널이 빌드됩니다.
힙 초기화의 경우 GKI는 CONFIG_INIT_ON_ALLOC_DEFAULT_ON을 사용하므로 모든 페이지 힙, SLAB, SLUB 할당이 만들어질 때 0으로 초기화됩니다. 이 옵션은 init_on_alloc=1을 커널 부팅 시간 옵션으로 전달하는 것과 유사한 효과가 있습니다.
버그 신고
Google 도구는 디버깅에 도움이 되는 추가 정보가 포함된 유용한 버그 신고를 생성합니다. 추가 할당 및 할당 해제 스택 트레이스를 통해 지정된 할당의 수명 주기를 더욱 잘 파악할 수 있어 근본 원인이 되는 메모리 안전 버그를 훨씬 빠르게 찾아낼 수 있습니다.
그림 1: 메모리 안전 도구에서 생성된 버그 신고
개발 중에 공급업체는 /data/tombstones 및 logcat에서 네이티브 충돌이 있는지 확인하여 버그의 존재를 모니터링해야 합니다. Android 네이티브 코드 디버깅에 관한 자세한 내용은 여기 정보를 참고하세요.
이 페이지에 나와 있는 콘텐츠와 코드 샘플에는 콘텐츠 라이선스에서 설명하는 라이선스가 적용됩니다. 자바 및 OpenJDK는 Oracle 및 Oracle 계열사의 상표 또는 등록 상표입니다.
최종 업데이트: 2025-07-27(UTC)
[[["이해하기 쉬움","easyToUnderstand","thumb-up"],["문제가 해결됨","solvedMyProblem","thumb-up"],["기타","otherUp","thumb-up"]],[["필요한 정보가 없음","missingTheInformationINeed","thumb-down"],["너무 복잡함/단계 수가 너무 많음","tooComplicatedTooManySteps","thumb-down"],["오래됨","outOfDate","thumb-down"],["번역 문제","translationIssue","thumb-down"],["샘플/코드 문제","samplesCodeIssue","thumb-down"],["기타","otherDown","thumb-down"]],["최종 업데이트: 2025-07-27(UTC)"],[],[],null,["# Zero initialized memory\n\nUninitialized memory in C and C++ is a common cause of reliability problems,\nmemory safety bugs and information leaks. To avoid these issues, Android\ninitializes as much memory as possible.\n\nZero initialized userspace memory\n---------------------------------\n\n\nSince Android 12, stack memory is zero initialized\nin all platform native code (including JNI) and heap memory is zero\ninitialized in all platform native processes (such as `netd`)\nbut not in the `zygote` or in apps.\n\n\nFirst and third-party apps built with the NDK are strongly\nrecommended to use the `-ftrivial-auto-var-init=zero` [compiler flag](https://cs.android.com/android/platform/superproject/+/android-latest-release:build/soong/cc/config/global.go;l=183;drc=bd20ccb83ef87bba9fdf31a937ccb7b921d67b73) to zero-initialize their stack local\nvariables. The compiler optimizes away any zeroing that is unnecessary.\nFor example, when a local variable is explicitly initialized\n(such as, `int x = 123;` variable `x` is initialized only once).\nIf the program has a large stack buffer in a performance\nhotspot, the developer can disable initialization using a compiler\nattribute:\n`\n__attribute__((__uninitialized__)) char buf[BUFSIZ];\n`\n\n\nApps can also opt in to heap zero initialization by using the\n`android:nativeHeapZeroInitialized` manifest attribute.\nAlternatively, heap zero initialization can be controlled at runtime\nwith:\n`\nint mallopt(M_BIONIC_ZERO_INIT, level)\n`\n\n\nWhere level is 0 or 1.\n| **Note:** Arm MTE implicitly zero-initializes almost all heap memory, with the exception of a small number of large heap allocations. We encourage C/C++ developers to use zero initialized memory wherever possible.\n\nZero initialized kernel memory\n------------------------------\n\n\nThe kernel stack and heap is zero initialized for GKI kernels, which is [strongly\nrecommended by the CDD](/docs/compatibility/13/android-13-cdd#97_security_features).\n\n\nFor stack initialization, GKI uses the\n`CONFIG_INIT_STACK_ALL_ZERO` config, which results in building the\nkernel using the `-ftrivial-auto-var-init=zero` compiler flag.\nFor heap initialization, GKI uses the\n`CONFIG_INIT_ON_ALLOC_DEFAULT_ON`, which makes all page heap, SLAB\nand SLUB allocations zero-initialized when they are created. This option is\neffectively similar to passing `init_on_alloc=1` as a kernel\nboot-time option.\n\nBug reports\n-----------\n\n\nOur tools generate insightful bug reports that contain additional information\nto aid with debugging. The additional allocation and deallocation stack trace\nhelp better understand the life cycle of a given allocation and lead to\nroot-causing memory safety bugs much faster.\n**Figure 1**: Bug reports generated by memory safety tools\n\n\nDuring development, vendors should monitor the presence of bugs by checking\n`/data/tombstones` and\n`logcat` for native crashes. For more information on\ndebugging Android native code see the information [here](/devices/tech/debug)."]]