gazpachoking / jsonref

Automatically dereferences JSON references within a JSON document.
http://jsonref.readthedocs.org
MIT License
122 stars 28 forks source link

Wrong reference resolve due to memory reuse. #61

Open xia-xiao opened 1 year ago

xia-xiao commented 1 year ago

For

def _walk_refs(obj, func, replace=False, _processed=None):
    # Keep track of already processed items to prevent recursion
    _processed = _processed or {}
    oid = id(obj)
    if oid in _processed:
        return _processed[oid]
    if type(obj) is JsonRef:
        r = func(obj)
        obj = r if replace else obj
    _processed[oid] = obj
    if isinstance(obj, Mapping):
        for k, v in obj.items():
            r = _walk_refs(v, func, replace=replace, _processed=_processed)
            if replace:
                obj[k] = r
    elif isinstance(obj, Sequence) and not isinstance(obj, str):
        for i, v in enumerate(obj):
            r = _walk_refs(v, func, replace=replace, _processed=_processed)
            if replace:
                obj[i] = r
    return obj

The memory of obj might be released if obj has been updated. Another object might occupied that piece of memory later. Then, id of it will be identical to the original one which causing return the wrong reference.