Re: [Dev-C++] Stress with structs and pointers.
Open Source C & C++ IDE for Windows
Brought to you by:
claplace
|
From: Per W. <pw...@ia...> - 2003-06-12 16:57:33
|
memset() works very well in C programs. However, there are some
things to remember about memset() on structures.
If the code is later moved to C++, and the struct gets virtual methods,
the memset() code will be deadly, since it will clear the address of the
virtual method table (VMT), which will make calls to the methods kill the
program. Also, the VMT is normally used for run-time type checking, such
as dynamic cast.
One more thing about memset() of structures is that in C++, the struct may
contain members that are themself classes with a constructor. The work
done by these constructors will be overwritten.
Memset of structures that are part of a multiple-inherritance aggregate is
also dangerous, since it kills the hidden fields the compiler added to
safely locate the addresses of the different base classes.
Note that most of the time, it is enough to just write:
struct mystruct s =3D {0};
and then the compiler will assign zero to all members of the structure.
This kind of initialization is directly portable to c++ without any
dangerous side effects.
/Per W
On Thu, 12 Jun 2003, OROSZI Bal=E1zs wrote:
> David McKen wrote:
> > Ok, I need some clarification on a couple topics invloving pointers and
> > pointers.
> >
> > 1) when a struct is created. All that can be assumed is that it contain=
s
> > trash right? What is a portable way to initalize everything to 0? mset?
>
> That is the simplest, if you have a LARGE structure.
>
> #include <mem.h> /* or string.h, I'm not sure */
>
> struct mystruct {
> int a,b,c;
> char d,e,f;
> long g,h,i,j,k,l,m,n;
> /* ... */
> };
>
> int main()
> {
> struct mystruct ms;
> memset(&ms,0,sizeof(struct mystruct));
> return 0;
> }
>
>
> The above code is pure C. In C++, you don't need the "struct" word, when
> using mystruct. So, in C++, the first 2 line in main():
>
> mystruct ms;
> memset(&ms,0,sizeof(mystruct));
>
> memset() is also portable, and it will always work, even if you alter
> the definition of your structure (add new elements). This way, you don't
> have to use a LONG list to set everything to 0.
>
> --
> Greetings,
> Bal=E1zs
>
>
>
> -------------------------------------------------------
> This SF.NET email is sponsored by: eBay
> Great deals on office technology -- on eBay now! Click here:
> http://adfarm.mediaplex.com/ad/ck/711-11697-6916-5
> _______________________________________________
> Dev-cpp-users mailing list
> Dev...@li...
> TO UNSUBSCRIBE: http://www.noicys.cjb.net/devcpp/ub.htm
> https://lists.sourceforge.net/lists/listinfo/dev-cpp-users
>
|