Skip to content

memory leak with Data::fastSet #19852

@JohnCoconut

Description

@JohnCoconut

cocos2d-x version: current v3 branch

void Data::fastSet(unsigned char* bytes, const ssize_t size)
{
CCASSERT(size >= 0, "fastSet size should be non-negative");
//CCASSERT(bytes, "bytes should not be nullptr");
_bytes = bytes;
_size = size;
}

fastSet makes the Data object managing a new memory area in [bytes, bytes + size), but it doesn't releasing the old data it manages. Failing to release the old data causes memory leak, as happens below,

Data ret = defaultValue;
if (encodedData)
{
unsigned char * decodedData = nullptr;
int decodedDataLen = base64Decode((unsigned char*)encodedData, (unsigned int)strlen(encodedData), &decodedData);
if (decodedData) {
ret.fastSet(decodedData, decodedDataLen);
}
}

Can be tested with the following example using valgrind

int main(int argc, char **argv)
{
     UserDefault *userDefault = UserDefault::getInstance();
     Data defaultValue;
     unsigned char *someData = (unsigned char*)malloc(100);
     defaultValue.fastSet(someData, 100);
     Data newData = userDefault->getDataForKey("int_data", defaultValue);
}

with the following UserDefault.xml file,

<?xml version="1.0" encoding="UTF-8"?>
<userDefaultRoot>
    <int_data>BQAAAAQAAAADAAAAAgAAAAEAAAAAAAAA</int_data>
    <float_data>AACgQAAAgEAAAEBAAAAAQAAAgD8AAAAA</float_data>
    <double_data>AAAAAAAAFEAAAAAAAAAQQAAAAAAAAAhAAAAAAAAAAEAAAAAAAADwPwAAAAAAAAAA</double_data>
</userDefaultRoot>

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions