Skip to content

random: Rely on free(NULL) being safe for random status freeing #10246

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jan 10, 2023
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 6 additions & 7 deletions ext/random/random.c
Original file line number Diff line number Diff line change
Expand Up @@ -234,7 +234,7 @@ static zend_object *php_random_randomizer_new(zend_class_entry *ce)
static void randomizer_free_obj(zend_object *object) {
php_random_randomizer *randomizer = php_random_randomizer_from_obj(object);

if (randomizer->is_userland_algo && randomizer->status) {
if (randomizer->is_userland_algo) {
php_random_status_free(randomizer->status, false);
}

Expand All @@ -261,9 +261,11 @@ PHPAPI php_random_status *php_random_status_copy(const php_random_algo *algo, ph

PHPAPI void php_random_status_free(php_random_status *status, const bool persistent)
{
if (status->state) {
pefree(status->state, persistent);
if (status == NULL) {
return;
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can status ever be NULL or should an assertion be added?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

See https://chat.stackoverflow.com/transcript/message/55792527#55792527 for context. I'm used to free()-style functions being a noop if passed NULL and consider it a good thing, because is avoids checking for NULL in every place that frees something that might be absent. In this case there might be no such place, but still this should just work in case there is.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've just restructured the method a little, though. Instead of returning early, it checks for NULL before dereferencing status and just passes a possible-NULL status to pefree(). This pattern is a little more common for more complex structs.


pefree(status->state, persistent);
pefree(status, persistent);
}

Expand All @@ -285,10 +287,7 @@ PHPAPI void php_random_engine_common_free_object(zend_object *object)
{
php_random_engine *engine = php_random_engine_from_obj(object);

if (engine->status) {
php_random_status_free(engine->status, false);
}

php_random_status_free(engine->status, false);
zend_object_std_dtor(object);
}

Expand Down