1. 程式人生 > >Python原始碼學習十一 一個常用的記憶體分配函式

Python原始碼學習十一 一個常用的記憶體分配函式

void *
_PyObject_DebugMallocApi(char id, size_t nbytes)
{
    uchar *p;           /* base address of malloc'ed block */
    uchar *tail;        /* p + 2*SST + nbytes == pointer to tail pad bytes */
    size_t total;       /* nbytes + 4*SST */

    bumpserialno();
    total = nbytes + 4*SST;
    if (total < nbytes)
        /* overflow:  can't represent total as a size_t */
        return NULL;

    p = (uchar *)PyObject_Malloc(total);
    if (p == NULL)
        return NULL;

    /* at p, write size (SST bytes), id (1 byte), pad (SST-1 bytes) */
    write_size_t(p, nbytes);
    p[SST] = (uchar)id;
    memset(p + SST + 1 , FORBIDDENBYTE, SST-1);

    if (nbytes > 0)
        memset(p + 2*SST, CLEANBYTE, nbytes);

    /* at tail, write pad (SST bytes) and serialno (SST bytes) */
    tail = p + 2*SST + nbytes;
    memset(tail, FORBIDDENBYTE, SST);
    write_size_t(tail + SST, serialno);

    return p + 2*SST;
}

SST是巨集定義 4
執行的實際作用是把nbytes的值(360 in this case)寫在記憶體區的前四個位元組,然後是一個uchar型的id , 'o' in this case
接著是nbytes個浩浩蕩蕩的0xcb
然後是4個oxfb, 和hex形式的serialno


(PyFrameObject*)op0x00b25528
(*((PyFrameObject*)op)).f_localsplus0x00b25668


我們看到f_localsplus的值正是 op + offset

offset is the f_localsplus offset in PyFrameObject definition