Home > other >  How do I clear a struct if I can't use memset?
How do I clear a struct if I can't use memset?

Time:09-10

I'm working with a piece of C code previously compiled (for x86) with clang . In converting to gcc, I'm seeing an error on the following line:

    memset(tracking, 0, sizeof(dbg_log_tracking_t));

I understand that I can't memset a 'non-trivial' (compiler's words) class, or something with a vtable, but this is a struct, it's a block of memory and nothing more, yet on compile, g tells me that I can't clear an object of a non-trivial type.

I'm being given a pointer as a buffer, and I will read data into that buffer from a phy, and the struct is then used to unpack. This struct needs to be zeroed before the read is done.

In C, I could happily shoot myself in the foot. I could memset main() to null if I so chose, and it's quite frustrating that I cannot do so here.

The only solution I can think of is to keep a static instance of this struct that is already zeroed, and memcpy it over, but that just seems like memset with extra steps and wasted memory.

Short of writing a clear function that hits every field of this specific struct (which would have to be done any time I ever want to do this), how do I zero an entire struct?

CodePudding user response:

if you are using C 11 or superior

tracking = {};

should work

CodePudding user response:

I think what you want is:

memset(&tracking, 0, sizeof(dbg_log_tracking_t));
//     ^ Note ampersand

I am making the assumption that tracking is an instance of your struct.

i.e.

dbg_log_tracking_t tracking;
memset(&tracking, 0, sizeof(tracking));  // I think this is more readable
  • Related