PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, September 10, 2022

[FIXED] How should I properly initialize a C struct from C++?

 September 10, 2022     c++, cross-platform, initialization     No comments   

Issue

I have the following code in a C++ file:

#include <sys/socket.h>

// ...
void someFunc() {
    struct msghdr msg = {0};  // <<< Uninitialized member here
}

When I compile with g++ using -Wall -Wextra, I get warnings:

error: missing initializer for member 'msghdr::msg_namelen'
...same for several other fields

My problem is this: I can't explicitly initialize all the fields, because I don't know what fields will exist (cross-platform) in a struct msghdr. The struct doesn't have a default constructor, since it's a C struct. I was under the impression that the = {0} form led to zero-initialization of all fields (which would be fine for me), but the g++ error message suggests not.

What are my options here?


Solution

Do this:

void someFunc()
{
    msghdr msg = {};  // <<< All members zero-initialized
}

The g++ -Wextra warning level is IMHO not very useful.

The code that you have is also formally OK for a "C struct", in standardeese known as POD (plain old data structure). But your code explicitly initializes the first member with 0. That won't necessarily work for an aggregate that isn't POD, e.g., with a std::string as the first member, while the pure {} will work also for that.

In passing, often a POD like the one you're dealing with has a byte count as the first member, and then you can do like …

void foo()
{
    SomePODStruct o = {sizeof(o)};    // The other members zero-initialized.
}

Perhaps add a STATIC_ASSERT that the byte count member is first (at offset 0).



Answered By - Cheers and hth. - Alf
Answer Checked By - Katrina (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing