473,714 Members | 2,500 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

memset on structs with non-PODs

Dear all,

I have an existing piece of code with a struct with some PODs.

struct A
{
int x;
int y;
};

This struct is created somewhere and initialized via a memset.

A a;
memset(&a,0,siz eof(A));

Now I want to extend the structure with an object, e.g a vector:

struct A
{
int x;
int y;
std::vector<int > z;
};

The sequence

A a;
memset(&a,0,siz eof(A));

would be fatal now, because I overwrite the instanciated vector a.z.
In reality the struct is very huge with a bunch of PODs inside, so using a
ctor would be possible, but quite a lot of work. (I am also scared to miss
something). How would you proceed to avoid the devastating memset?
I thought of kind of

struct A
{
int x;
int y;
int no_memsetbeyond _this_point;
std::vector<int > z;
};

and

A a;
memset(&a,0,&a. no_memsetbeyond _this_point-&a);

It is not really nice, but I have to avoid as much code-rework as possible
for the moment.

Kind regards,
Patrick
Jan 19 '06 #1
14 8446
* Patrick Kowalzick:
Dear all,

I have an existing piece of code with a struct with some PODs.

struct A
{
int x;
int y;
};

This struct is created somewhere and initialized via a memset.

A a;
memset(&a,0,siz eof(A));

Now I want to extend the structure with an object, e.g a vector:

struct A
{
int x;
int y;
std::vector<int > z;
};
When you have public non-POD members you need to redesign.

The sequence

A a;
memset(&a,0,siz eof(A));

would be fatal now, because I overwrite the instanciated vector a.z.
In reality the struct is very huge with a bunch of PODs inside, so using a
ctor would be possible, but quite a lot of work. (I am also scared to miss
something). How would you proceed to avoid the devastating memset?


When you a "very huge" struct you need to redesign.

But possibly you need to practice that on some smaller test programs
first.

For now, rename the orginal struct to PodA,

struct PodA { ... };

then derive struct A from that,

struct A: PodA
{
A(): PodA() {}
std::vector<int > z;
};

and also check that your compiler supports default-initialization of
POD's (unfortunately some don't).

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Jan 19 '06 #2
Hello Alf,
struct A
{
int x;
int y;
std::vector<int > z;
};
When you have public non-POD members you need to redesign.


Normally I'd never use struct for more complex things :).
In reality the struct is very huge with a bunch of PODs inside, so using
a
ctor would be possible, but quite a lot of work. (I am also scared to
miss
something). How would you proceed to avoid the devastating memset?


When you a "very huge" struct you need to redesign.


Hmm, might be. Lets say very huge in this context is nothing elses than: I
do not want to initialize all the members.
For now, rename the orginal struct to PodA,

struct PodA { ... };

then derive struct A from that,

struct A: PodA
{
A(): PodA() {}
std::vector<int > z;
};
Perfect. Thats a rather good solution. Anyway for this case I will change to

struct PodA
{
PodA() { memset(this,0,s izeof(PodA)); }
...
};

struct A: PodA
{
std::vector<int > z;
};

This is not nice (ok it is ugly), but closer to the original code.
and also check that your compiler supports default-initialization of
POD's (unfortunately some don't).


I can not, as support for different compiliers has to be assured.

Thanks, that's really good solution.

Regards,
Patrick
Jan 19 '06 #3
On Thu, 19 Jan 2006 14:57:34 +0100, "Patrick Kowalzick"
<pa************ ***@mapandguide .de> wrote:
Dear all,

I have an existing piece of code with a struct with some PODs.

struct A
{
int x;
int y;
};

This struct is created somewhere and initialized via a memset.

A a;
memset(&a,0,si zeof(A));

Now I want to extend the structure with an object, e.g a vector:

struct A
{
int x;
int y;
std::vector<int > z;
};

The sequence

A a;
memset(&a,0,si zeof(A));

would be fatal now, because I overwrite the instanciated vector a.z.

<snip>

You may create a non-virtual base class with only POD data and inherit
from it. In such a way, you could still a memset, but only with thiis
base class.

struct A_
{
int x;
int y;
};

struct A:public A_
{
A() {memset(static_ cast<A_ *>(this),0,size of(A_);}
std::vector<int > z;
};

Regards,

Zara
Jan 19 '06 #4

Patrick Kowalzick wrote:
Dear all,

I have an existing piece of code with a struct with some PODs.

struct A
{
int x;
int y;
};

This struct is created somewhere and initialized via a memset.


[]

Overload memset() in the same header where A is declared:

void memset(A*, int, size_t);

Note that this overload won't be called if memset is invoked as:

memset(void*)&a , ...);

A more proper way would be to redesign the code, so that it don't do
memset on A's anymore.

Jan 19 '06 #5

Alf P. Steinbach wrote:
* Patrick Kowalzick:
Dear all,

I have an existing piece of code with a struct with some PODs.

struct A
{
int x;
int y;
};

This struct is created somewhere and initialized via a memset.

A a;
memset(&a,0,siz eof(A));

Now I want to extend the structure with an object, e.g a vector:

struct A
{
int x;
int y;
std::vector<int > z;
};


I have a follow on question to this. Given:

unsigned int const max_id = 5;
unsigned int const max_participant s = 5;
struct some_struct
{ int some_param;
some_struct()
: some_param( -1) {}
};

struct some_other_stru ct
{ int some_var;
int some_size;
unsigned char* ptr;
some_other_stru ct()
: some_var(-1)
, some_size(-1)
, ptr(0)
{}
};

struct someImportantDa ta {
unsigned int c_style_arr[ max_participant s ];
some_struct c_style_arr2[ max_id ] [ max_participant s ];
some_other_stru ct c_style_arr3[ max_participant s ];
};
int main()
{
someImportantDa ta sid;
for ( int idx(0); idx < max_participant s; ++idx )
{
sid.c_style_arr[ idx ] = idx ;
}
typedef std::vector<uns igned int> UINT_VEC;
UINT_VEC myVec(&sid.c_st yle_arr[0],
&sid.c_style_ar r[max_participant s] );

UINT_VEC::itera tor end = myVec.end();
for ( UINT_VEC::const _iterator it = myVec.begin(); it != end; ++it )
{
std::cout << *it << std::endl;
}

}

Now going from c_style_arr to a vector is easy (as shown below) .
How would I do the c_style_arr2 and c_style_arr3? Part of the issue
with c_sytle_arr2 is based on the fact that I'm still experimenting
with 2-d vectors.

In any event, thanks in advance.

Jan 19 '06 #6
Hello Maxim,
I have an existing piece of code with a struct with some PODs.

struct A
{
int x;
int y;
};

This struct is created somewhere and initialized via a memset.


[]

Overload memset() in the same header where A is declared:

void memset(A*, int, size_t);

Note that this overload won't be called if memset is invoked as:

memset(void*)&a , ...);

A more proper way would be to redesign the code, so that it don't do
memset on A's anymore.


The memset are not too often, so I kicked them :). But it seems to be a good
idea to overload memset, perhaps I missed one.....

void memset(A*, int, size_t)
{
assert( "Please, please do not use memset for this struct");
}

Hmm, or static_assert? Would something like this work as static assert?

// forward for allowed memsets
template < typename T > class memset_functor
{
public:
void * operator()( T* dest, int c, size_t count )
{
return memset(dest,c,c ount);
}
};

// forward for disallowed memsets
template <> class memset_functor< A >
{
public:
void * operator()( A *, int, size_t )
{
// STATIC_ASSERTIO N
}
};

template < typename T >
void * memset( T* dest, int c, size_t count )
{
return memset_functor< T>()(dest,c,cou nt);
}

Looks funny. I will test this towmorrow :)

Regards,
Patrick
Jan 19 '06 #7

"Patrick Kowalzick" <pa************ ***@mapandguide .de> skrev i
meddelandet news:ne******** ************@pr oxy.mapandguide .de...
Hello Alf,
struct A
{
int x;
int y;
std::vector<int > z;
};
When you have public non-POD members you need to redesign.


Normally I'd never use struct for more complex things :).
In reality the struct is very huge with a bunch of PODs inside, so
using a
ctor would be possible, but quite a lot of work. (I am also scared
to miss
something). How would you proceed to avoid the devastating memset?


When you a "very huge" struct you need to redesign.


Hmm, might be. Lets say very huge in this context is nothing elses
than: I do not want to initialize all the members.
For now, rename the orginal struct to PodA,

struct PodA { ... };

then derive struct A from that,

struct A: PodA
{
A(): PodA() {}
std::vector<int > z;
};


Perfect. Thats a rather good solution. Anyway for this case I will
change to

struct PodA
{
PodA() { memset(this,0,s izeof(PodA)); }
...
};

But now you have a constructor, so it's not a POD anymore. :-(

This is not nice (ok it is ugly), but closer to the original code.


It is ugly!
Bo Persson

Jan 19 '06 #8
> Hmm, or static_assert? Would something like this work as static assert?

// forward for allowed memsets
template < typename T > class memset_functor
{
public:
void * operator()( T* dest, int c, size_t count )
{
return memset(dest,c,c ount);
}
};

// forward for disallowed memsets
template <> class memset_functor< A >
{
public:
void * operator()( A *, int, size_t )
{
// STATIC_ASSERTIO N
}
};

template < typename T >
void * memset( T* dest, int c, size_t count )
{
return memset_functor< T>()(dest,c,cou nt);
}

Looks funny. I will test this towmorrow :)


Ok. I tried it, and it does not work.

The specialization memset_functor< A > will be instanciated, even if there
is no call "memset(A,int,s ize_t)". Like this the static assertion always
fails.

I use now an easier approach, which works on my compiler, but I am not sure
if it is bullet proof:

template < typename T >
void * memset( TTransferDistli bData2 * dest, T c, size_t count )
{
BOOST_STATIC_AS SERT(FALSE);
return NULL;
}

Calling memset(A,..) fails like this to compile.

Kind regards,
Patrick
Jan 20 '06 #9
Hello Bo,
Perfect. Thats a rather good solution. Anyway for this case I will change
to

struct PodA
{
PodA() { memset(this,0,s izeof(PodA)); }
...
};

But now you have a constructor, so it's not a POD anymore. :-(


Hmm, ok. I call it "public class with only PODs inside" :).
This is not nice (ok it is ugly), but closer to the original code.


It is ugly!


no choice.

Regards,
Patrick
Jan 20 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
6236
by: Joe C | last post by:
I'm a hobbiest, and made the forray into c++ from non-c type languages about a year ago. I was "cleaning up" some code I wrote to make it more "c++ like" and have a few questions. I'm comfortable using new/delete when dealing with arrays, and, so-far haven't used the STL (eg vectors) very much when dealing with POD. I'm using a class to dump files into. The class puts the file data into a 32-bit array, then offers both 32-bit and char*...
17
19951
by: Nollie | last post by:
Say you have a struct: struct MYSTRUCT { int x; int y; int w; int h; };
6
8256
by: bob_jenkins | last post by:
{ const void *p; (void)memset((void *)p, ' ', (size_t)10); } Should this call to memset() be legal? Memset is of type void *memset(void *, unsigned char, size_t) Also, (void *) is the generic pointer type. My real question is, is (void *) such a generic pointer type that it
27
5219
by: volunteers | last post by:
I met a question about memset and have no idea right now. Could anybody give a clue? Thanks memset is sometimes used to initialize data in a constructor like the example below. What is the benefit of initializing this way? Does it work in this example? Does it work in general ? Is it a good idea in general? class A { public:
18
11978
by: dykeinthebox | last post by:
Consider the following program: #include <stdlib.h> #include <string.h> int main( void ) { void *p = malloc( 4 ); if ( p ) {
43
3816
by: JohnQ | last post by:
Are a default constructor, destructor, copy constructor and assignment operator generated by the compiler for a struct if they are not explicitely defined? I think the answer is yes, because "there is no difference between a struct and a class except the public/private access specification" (and a few minor other things). When I create a class, I always start by declaring the default constructor, copy constructor and assignment operator...
13
2525
by: JohnQ | last post by:
The implementation of classes with virtual functions is conceptually easy to understand: they use vtables. Which begs the question about POD structs: how are they associated with their member functions in common implementations? And where is the 'this' ptr tucked away at for POD structs with member functions? John
12
3579
by: Martin Wells | last post by:
I'm trying to come up with a fully-portable macro for supplying memset with an unsigned char rather than an int. I'm going to think out loud as I go along. . . I'll take a sample system before I begin: CHAR_BIT == 16 sizeof(short) == sizeof(int) == 1 Assume none of the integer types have padding bits Sign-magnitude
18
783
by: Gaijinco | last post by:
I'm having a headache using memset() Given: int v; memset((void*)v, 1, sizeof(v)); Can I be 100% positive than v = 1 for i 0, or there is something else I have to do?.
32
13620
by: viza | last post by:
Hi all Is this assertion guaranteed? { void *vptr; memset( & vptr, 0, sizeof vptr); assert( NULL == vptr ); } What about these ones?
0
8707
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9314
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
7953
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6634
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5947
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4464
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4725
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2520
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2110
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.