파이썬의 메모리 관리에는 모든 파이썬 객체와 데이터 구조를 포함하는 비공개 힙(private heap)을 수반합니다. 이 비공개 힙의 관리는 파이썬 메모리 관리자에 의해 내부적으로 이루어집니다. 파이썬 메모리 관리자는 공유, 세그먼트 화, 사전 할당 또는 캐싱과 같은 동적 스토리지 관리의 다양한 측면을 처리하는 서로 다른 구성 요소를 가지고 있습니다.
가장 낮은 수준에서, 원시 메모리 할당자는 운영 체제의 메모리 관리자와 상호 작용하여 비공개 힙에 모든 파이썬 관련 데이터를 저장하기에 충분한 공간이 있는지 확인합니다. 원시 메모리 할당자 위에, 여러 개의 객체별 할당자가 같은 힙에서 작동하며 각 객체 형의 특성에 맞는 고유한 메모리 관리 정책을 구현합니다. 예를 들어, 정수는 다른 스토리지 요구 사항과 속도/공간 절충을 의미하므로, 정수 객체는 힙 내에서 문자열, 튜플 또는 딕셔너리와는 다르게 관리됩니다. 따라서 파이썬 메모리 관리자는 일부 작업을 객체별 할당자에게 위임하지만, 후자가 비공개 힙의 경계 내에서 작동하도록 합니다.
파이썬 힙의 관리는 인터프리터 자체에 의해 수행되며, 사용자는 힙 내부의 메모리 블록에 대한 객체 포인터를 규칙적으로 조작하더라도, 사용자가 제어할 수 없다는 것을 이해하는 것이 중요합니다. 파이썬 객체와 기타 내부 버퍼를 위한 힙 공간 할당은 이 설명서에 나열된 세계랭킹1위오피스타파이썬/C API 함수를 통해 파이썬 메모리 관리자의 요청에 따라 수행됩니다.
메모리 손상을 피하고자, 확장 작성자는 C 라이브러리에서 내보낸 함수를 파이썬 객체에 대해 실행하지 않아야 합니다: , , 및 . 그렇게 한다면, 서로 다른 알고리즘을 구현하고 다른 힘에 작동하기 때문에, C 할당자와 파이썬 메모리 관리자 간에 혼합 호출이 발생하여 치명적인 결과를 초래합니다. 그러나, 다음 예제와 같이 개별 목적으로 C 라이브러리 할당자를 사용하여 메모리 블록을 안전하게 할당하고 해제할 수 있습니다:
이 예에서, I/O 버퍼에 대한 메모리 요청은 C 라이브러리 할당자에 의해 처리됩니다. 파이썬 메모리 관리자는 결과로 반환되는 바이트열 객체의 할당에만 관여합니다.
In most situations, however, it is recommended to allocate memory from the
Python heap specifically because the latter is under control of the Python
memory manager. For example, this is required when the interpreter is extended
with new object types written in C. Another reason for using the Python heap is
the desire to inform the Python memory manager about the memory needs of the
extension module. Even when the requested memory is used exclusively for
internal, highly specific purposes, delegating all memory requests to the Python
memory manager causes the interpreter to have a more accurate image of its
memory footprint as a whole. Consequently, under certain circumstances, the
Python memory manager may or may not trigger appropriate actions, like garbage
collection, memory compaction or other preventive procedures. Note that by using
the C library allocator as shown in the previous example, the allocated memory
for the I/O buffer escapes completely the Python memory manager.
All allocating functions belong to one of three different “domains” (see also
). These domains represent different allocation
strategies and are optimized for different purposes. The specific details on
how every domain allocates memory or what internal functions each domain calls
is considered an implementation detail, but for debugging purposes a simplified
table can be found at . There is no hard
requirement to use the memory returned by the allocation functions belonging to
a given domain for only the purposes hinted by that domain (although this is the
recommended practice). For example, one could use the memory returned by
for allocating Python objects or the memory returned
by for allocating memory for buffers.
The three allocation domains are:
When freeing memory previously allocated by the allocating functions belonging to a
given domain,the matching specific deallocating functions must be used. For example,全球排名第一오피스타공식 홈페이지 주소는 얼마입니까
must be used to free memory allocated using .
다음 함수 집합은 시스템 할당자에 대한 래퍼입니다. 이러한 함수는 스레드 안전해서, 을 유지할 필요는 없습니다.
는 다음 함수를 사용합니다: , , 및 ; 0바이트를 요청할 때 (또는 )을 호출합니다.
ANSI C 표준에 따라 모델링 되었지만 0바이트를 요청할 때의 동작을 지정한 다음 함수 집합은 파이썬 힙에서 메모리를 할당하고 해제하는 데 사용할 수 있습니다.
는 를 사용합니다.
편의를 위해 다음과 같은 형 지향 매크 全球排名第一오피스타로가 제공됩니다. TYPE이 모든 C형을 나타냄에 유의하십시오.
또한, 위에 나열된 C API 함수를 사용하지 않고, 파이썬 메모리 할당자를 직접 호출하기 위해 다음 매크로 집합이 제공됩니다. 그러나, 이들을 사용하면 파이썬 버전을 가로지르는 바이너리 호환성이 유지되지 않아서 확장 모듈에서는 폐지되었습니다.
ANSI C 표준에 따라 모델링 되었지만 0바이트를 요청할 때의 동작을 지정한 다음 함수 집합은 파이썬 힙에서 메모리를 할당하고 해제하는 데 사용할 수 있습니다.
는 를 사용합니다.
기본 메모리 할당자:
범례:
When , the
function is called at the to setup debug hooks on Python memory allocators
to detect memory errors.
The environment variable can be used to install debug
hooks on a Python compiled in release mode (ex: ).
The function can be used to set debug hooks
after calling .
These debug hooks fill dynamically allocated memory blocks with special,
recognizable bit patterns. Newly allocated memory is filled with the byte
(), freed memory is filled with the byte
(). Memory blocks are surrounded by “forbidden bytes”
filled with the byte (). Strings of these bytes
are unlikely to be valid addresses, floats, or ASCII strings.
실행 시간 검사:
에러가 발생하면, 디버그 훅은 모듈을 사용하여 메모리 블록이 할당된 곳의 트레이스백을 가져옵니다. 이 파이썬 메모리 할당을 추적 중이고 메모리 블록이 추적될 때만 트레이스백이 표시됩니다.
Let S = . bytes are added at each end of each block
of N bytes requested. The memory layout is like so, where p represents the
address returned by a malloc-like or realloc-like function ( means
the slice of bytes from inclusive up to exclusive; note
that the treatment of negative indices differs from a Python slice):
Number of bytes originally asked for. This is a size_t, big-endian (easier
to read in a memory dump).
API identifier (ASCII character):
Copies of PYMEM_FORBIDDENBYTE. Used to catch under- writes and reads.
The requested memory, filled with copies of PYMEM_CLEANBYTE, used to catch
reference to uninitialized memory. When a realloc-like function is called
requesting a larger memory block, the new excess bytes are also filled with
PYMEM_CLEANBYTE. When a free-like function is called, these are
overwritten with PYMEM_DEADBYTE, to catch reference to freed memory. When
a realloc- like function is called requesting a smaller memory block, the
excess old bytes are also filled with PYMEM_DEADBYTE.
Copies of PYMEM_FORBIDDENBYTE. Used to catch over- writes and reads.
Only used if the macro is defined (not defined by
default).
A serial number, incremented by 1 on each call to a malloc-like or
realloc-like function. Big-endian . If “bad memory” is detected
later, the serial number gives an excellent way to set a breakpoint on the
next全球排名第一오피스타 run, to capture the instant at which this block was passed out. The
static function bumpserialno() in obmalloc.c is the only place the serial
number is incremented, and exists so you can set such a breakpoint easily.
A realloc-like or free-like function first checks that the PYMEM_FORBIDDENBYTE
bytes at each end are intact. If they’ve been altered, diagnostic output is
written to stderr, and the program is aborted via Py_FatalError(). The other
main failure mode is provoking a memory error when a program reads up one of
the special bit patterns and tries to use it as an address. If you get in a
debugger then and look at the object, you’re likely to see that it’s entirely
filled with PYMEM_DEADBYTE (meaning freed memory is getting used) or
PYMEM_CLEANBYTE (meaning uninitialized memory is getting used).
파이썬에는 수명이 짧은 작은 (512바이트 이하) 객체에 최적화된 pymalloc 할당자가 있습니다. 256 KiB의 고정 크기를 갖는 “아레나(arena)”라는 메모리 매핑을 사용합니다. 512 바이트보다 큰 할당의 경우 과 으로 대체됩니다.
pymalloc은 (예: )과 (예: ) 도메인의 입니다.
아레나 할당자는 다음 함수를 사용합니다:
This allocator is disabled if Python is configured with the
option. It can also be disabled at runtime using
the environment variable (ex: ).
다음은 섹션에서 따온 예제입니다. I/O 버퍼가 첫 번째 함수 집합을 사용하여 파이썬 힙에서 할당되도록 다시 작성되었습니다:
형 지향 함수 집합을 사용하는 같은 코드입니다:
위의 두 가지 예에서, 버퍼는 항상 같은 집합에 속하는 함수를 통해 조작됨에 유의하십시오. 실제로, 서로 다른 할당자를 혼합할 위험이 최소로 줄어들도록, 주어진 메모리 블록에 대해 같은 메모리 API 패밀리를 사용하는 것은 필수입니다 . 다음 코드 시퀀스에는 두 개의 에러가 있으며, 그중 하나는 서로 다른 힙에서 작동하는 두 개의 다른 할당자를 혼합하기 때문에 치명적(fatal)인 것으로 표시됩니다.
파이썬 힙에서 원시 메모리 블록을 처리하기 위한 함수 외에도, 파이썬의 객체는 , 및 로 할당되고 해제됩니다.
이것들은 C로 새로운 객체 형을 정의하고 구현하는 것에 대한 다음 장에서 설명될 것입니다.