Skip to content

Potential inconsistency in BufferRaw::setCapacity method #251

@xiegd

Description

@xiegd

Issue Description

In the BufferRaw::setCapacity method (file: ZLToolKit/src/Network/Buffer.h), there seems to be a potential inconsistency in how the capacity is handled when _data is not null.

Current Behavior

The current implementation sometimes returns early without updating _capacity, which may lead to a mismatch between _capacity and the actual allocated memory size.

Code in Question

    void setCapacity(size_t capacity) {
        if (_data) {
            do {
                if (capacity > _capacity) {
                    // If the requested memory is greater than the current memory, reallocate
                    break;
                }

                if (_capacity < 2 * 1024) {
                    // Less than 2K, do not repeatedly allocate memory, reuse directly
                    return;
                }

                if (2 * capacity > _capacity) {
                    // If the requested memory is greater than half of the current memory, also reuse
                    return;
                }
            } while (false);

            delete[] _data;
        }
        _data = new char[capacity];
        _capacity = capacity;
    }

Issue Description

In the BufferRaw::setCapacity method (file: ZLToolKit/src/Network/Buffer.h), there seems to be a potential inconsistency in how the capacity is handled when _data is not null.

Current Behavior

The current implementation sometimes returns early without updating _capacity, which may lead to a mismatch between _capacity and the actual allocated memory size.

Code in Question

    void setCapacity(size_t capacity) {
        if (_data) {
            do {
                if (capacity > _capacity) {
                    //请求的内存大于当前内存,那么重新分配  [AUTO-TRANSLATED:65306424]
                    //If the requested memory is greater than the current memory, reallocate
                    break;
                }

                if (_capacity < 2 * 1024) {
                    //2K以下,不重复开辟内存,直接复用  [AUTO-TRANSLATED:056416c0]
                    //Less than 2K, do not repeatedly allocate memory, reuse directly
                    return;
                }

                if (2 * capacity > _capacity) {
                    //如果请求的内存大于当前内存的一半,那么也复用  [AUTO-TRANSLATED:c189d660]
                    //If the requested memory is greater than half of the current memory, also reuse
                    return;
                }
            } while (false);

            delete[] _data;
        }
        _data = new char[capacity];
        _capacity = capacity;
    }

TRANS_BY_GITHUB_AI_ASSISTANT

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions