推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
joeHuang
V2EX  ›  Python

Python 源码中 PyListObject 中的两个问题请教各位大神

  •  
  •   joeHuang · Mar 6, 2018 · 2706 views
    This topic created in 3015 days ago, the information mentioned may be changed or developed.
    问题一:在创建包含 size 个 PyObject *的 PyListObject 时,内存数量计算,溢出检查。部分代码如下
    int size;
    size_t nbytes = size * sizeof(PyObject *)
    if( nbytes/sizeof(PyObject *) != (size_t) size){
    return 溢出
    }
    这段代码判断溢出的思路是什么?

    问题二:在插入元素时,判断是否需要申请新的内存
    if (allocated >= newsize >= (allocated>>1)) 不申请新的内存
    else new_allocated = (newsize >> 3) + (newsize < 9?3:6)+newsize 申请 new_allocated 个新的内存

    这里 new_allocated 的计算逻辑是什么?为什么是这样计算的
    7 replies    2018-03-15 23:16:52 +08:00
    wangxn
        2
    wangxn  
       Mar 6, 2018 via Android   ❤️ 1
    能不能直接复制源码而不要用奇怪的伪码……
    gnaggnoyil
        3
    gnaggnoyil  
       Mar 6, 2018   ❤️ 1
    1 中的代码的本意是认为`size * sizeof(PyObject *)`只有在不发生溢出的情况下其值才是数学意义上相乘的结果.不过我很怀疑这段代码可能不能保证 portable:一个`int`和一个`size_t`相乘的结果不保证一定是个无符号的(比如`int`的 rank 严格大于`size_t`的时候).而有符号数溢出是未定义行为.我没怎么读过 CPython 源码,如果 CPython 源码真的是这么写的话我只能说这代码质量还是有待改进……
    gnaggnoyil
        4
    gnaggnoyil  
       Mar 6, 2018   ❤️ 2
    哦不对我傻了.我忘了有个东西叫做 Integer promotion. Integer promotion 的存在导致`int`的 rank 必然小于等于`size_t`进行 Integer promotion 之后的类型,所以两者相乘的结果必然是严格无符号的,所以这段代码应该是严格没问题的……
    joeHuang
        5
    joeHuang  
    OP
       Mar 14, 2018
    @wangxn 帖子里写的就是源码。
    joeHuang
        6
    joeHuang  
    OP
       Mar 14, 2018
    wangxn
        7
    wangxn  
       Mar 15, 2018 via Android
    @joeHuang 连分号都没有,能编译通过?
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1153 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 17:32 · PVG 01:32 · LAX 10:32 · JFK 13:32
    ♥ Do have faith in what you're doing.