Skip to content

Usage of memset with non-trivial types that results in -Wclass-memaccess #12684

@am11

Description

@am11

Starting with gcc 8, compiler is warning about several usages of memset in case of types that are
non-trivially copyable. This includes structs inheriting struct ZeroInit, usage of FillMemory and ZeroMemory macros (defined in pal.h) and other places which are directly calling the function (although some of those places can make use of the defined macro as it stands).

From release notes (https://www.gnu.org/software/gcc/gcc-8/changes.html):

-Wclass-memaccess warns when objects of non-trivial class types are manipulated in potentially unsafe ways by raw memory functions such as memcpy, or realloc. The warning helps detect calls that bypass user-defined constructors or copy-assignment operators, corrupt virtual table pointers, data members of const-qualified types or references, or member pointers. The warning also detects calls that would bypass access controls to data members.

LLVM has included -Wnontrivial-memaccess for C structs and there are also considerations to add -Wclass-memaccess in future: https://reviews.llvm.org/D45310

Reading the community discussions about practices pertaining to usage of memset with non-POD types and how others have responded to the gcc warning, I think there are three ways to fix this (in descending order of preference):

  1. Call proper ctor, use std:fill and friends for non-trivial data structures.
  2. Cast pointer to void* to circumvent the type check.
  3. Suppress warning in cmake -Wno-class-memaccess.

Metadata

Metadata

Labels

Type

No type

Projects

Relationships

None yet

Development

No branches or pull requests

Issue actions