Skip to content

Do not use FillChar to initialize records #150

Open
@Chadehoc

Description

@Chadehoc

Prerequisites

  • This rule has not already been suggested.
    This should be a new rule, not an improvement to an existing rule.
    This rule would be generally useful, not specific to my code or setup.

Suggested rule title

NoFillCharOnRecords

Rule description

Using FillChar or ZeroMemory to initialize a record can evolve badly if one adds a managed field to the record. If the Delphi version supports it, it is suggested to use := Default(T) instead.

This was suggested as part of #149, but is too dependent on using a recent Delphi version. Making it a separate rule is more adequate.

Rationale

Using FillChar on a managed field can skip a refcount Release and result in large memory leaks.

Activity

added
featureNew feature or request
ruleImprovements or additions to rules
triageThis needs to be triaged by a maintainer
on Dec 29, 2023
cirras

cirras commented on Dec 29, 2023

@cirras
Collaborator

Thanks for the suggestion!

Agreed that this is a very appropriate rule for new Delphi versions, where the Default intrinsic is unamibiguously the most correct tool for the job of default-initializing any variable.

I also like that you provided an example of why this code smell can lead to real-world bugs. 👍

removed
triageThis needs to be triaged by a maintainer
on Dec 29, 2023
sglienke

sglienke commented on Jan 10, 2024

@sglienke

FWIW using FillChar to initialize a record before use is not an issue because the compiler would have inserted appropriate code to initialize any managed fields into the prologue of the routine - the issue is using FillChar to clear an already used record that might contain some data in its managed fields.

cirras

cirras commented on Jan 10, 2024

@cirras
Collaborator

FWIW using FillChar to initialize a record before use is not an issue because the compiler would have inserted appropriate code to initialize any managed fields into the prologue of the routine - the issue is using FillChar to clear an already used record that might contain some data in its managed fields.

Thanks for the additional information, Stefan.
I think we should mention that subtlety of the behavior when writing the rule description.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    featureNew feature or requestruleImprovements or additions to rules

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @Chadehoc@sglienke@cirras

        Issue actions

          Do not use FillChar to initialize records · Issue #150 · integrated-application-development/sonar-delphi