Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

Memset 0 or 0x00 ?

Posted on 2014-02-26
12
Medium Priority
?
1,621 Views
Last Modified: 2014-03-15
I have a query on Memset, which one we need to use 0x00 or 0

Ex:
char myname[512]; //created a character array and wants to memset it
//Is there any difference in the below lines:
memset (&myname, 0, sizeof(myname));
memset (&myname, 0x00, sizeof(myname));  //some are saying we should use only this. 0x00 will be replaces the string with NULL.

I feel both are same. 0x00 will be converted into int as memset takes 2nd argument as int.

I have seen the visual studio also used both. so where we need to use these two types of memsets? 0x00 in which situation and 0 in which situation.?

 C:\program files\Microsoft Visual Studio 10.0\VC\atlmfc\include\atlcoll.h(2948):      
memset( ppBins, 0, nBins*sizeof( CNode* ) );
  C:\program files\Microsoft Visual Studio 10.0\VC\atlmfc\include\atlcoll.h(3554):      
memset(m_pNil, 0x00, sizeof(CNode));

Please clarify in detail.
0
Comment
Question by:priyanka999kamlekar
  • 4
  • 4
  • 3
  • +1
12 Comments
 
LVL 46

Expert Comment

by:Kent Olsen
ID: 39888604
Hi priyanka999kamlekar,

They are the same.  Zero is zero and C provides a number of ways to represent zero.  

Feel free to use whichever form makes the most sense to you, just try and be consistent.  Some people find that using '\0' to show a character of 0 is self-documenting.  Others find that that always using 0 regardless of the type is more meaningful.

Regardless, C will cast it to the correct length.

Kent
0
 
LVL 9

Expert Comment

by:Subrat (C++ windows/Linux)
ID: 39890804
As said in previous comment, you can use either  0x00 or 0.
 0x00 is hexadecimal representation of 0.but value wise these are same.
To make code readable we really choose what to use.

Moreover. you posted it in c++ tag, so I can tell one more win32 API, which performs the same thing
ZeroMemory()
memset() is C library function.
0
 
LVL 31

Expert Comment

by:Zoppo
ID: 39891280
Hi priyanka999kamlekar,

just as addition (and allthough I guess you already know about): for using such an array as string with common C/C++ string functions/classes it's not needed to set every char of the string to 0 to indicate an empty string, it's enough to set the first char to 0 with something like i.e.:

  char myname[512];
  myname[0] = '\0';

Beside this you can initialize the char array with all chars in it set to 0 automatically where you declare it i.e. like this:

  char myname[512] = {};

ZOPPO
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
LVL 9

Expert Comment

by:Subrat (C++ windows/Linux)
ID: 39893706
In C++, we can't write initialize arr[523]={} in constructor. and also in header also it is not possible.
// char myname[512] = {};
This only works for local variables.
So if we want to initialize data member arr[] in constructor, we have to use memset() or zeroMemory(). and also only arr[0]='\0' is not enough:)

More over, if you create object as follows, then automatically all elements of int array will be initialized to ZERO.

MyClassr* p = new MyClass();

But if use cppchecker or something similar to find out the warning,style,performance errors, then it'll complain if all data members are not initialized in constructor.
So ultimately we have use memset() or ZeroMemory() ...
0
 

Author Comment

by:priyanka999kamlekar
ID: 39894796
I am confused.
I am coding it in C only.
I have a structure which contain all type of data types even strucures too.
typedef struct tStruct
{
    char name[40];
    int id;
    double sal;
    long x,
    short y;

    Struct my_model
   {
        char name[40];
        int id;
       double size;
       long a;
       short b;
     }model;

}TSTRUCT;

Now can i do it this way.
TSTRUCT tempData = {};

or do i need to use memset.

TSTRUCT tempData;
memset(&tempData, 0, sizeof(tempData));

Can you tell me when to use memset in this case and if i have pointer variables how this memset will behave.?
Please clarify.
0
 
LVL 46

Expert Comment

by:Kent Olsen
ID: 39894822
You should use memset, or provide enough initializers to set all of the elements to zero.

typedef struct
{
  int i1;
  int i2;
} Example;

Example X = {0};
Example Y = {0, 0};

In the short example above, X.i1 gets initialized to zero, X.i2 does not get initialized.  Y.i1 and Y.i2 get initialized.

Note that X.i2 will be zero if the variable is create in the globals block (not within a function) as all items in the globals block default to zero.

A common practice is to initialize structure objects with memset.  It's fast and easy, and if programming changes ever result in the structure being changed, initialization is still automatic.

  memset (X, 0, sizeof (Example));


Good Luck,
Kent
0
 
LVL 9

Expert Comment

by:Subrat (C++ windows/Linux)
ID: 39896484
Using memset() you are telling to fill ZEROs(In this case) from starting address to a particular range. So it's a good discision.

>>>> if i have pointer variables how this memset will behave.?
Pointers will become NULL.which is required during initialization.
0
 
LVL 31

Accepted Solution

by:
Zoppo earned 1500 total points
ID: 39899890
IMO there's no need to use memset when it can be initialized directly. I tested it with VisualStudio 2010 C-compiler using this code:
typedef struct tStruct
{
	char	name[40];
	int		id;
	double	sal;
	long	x;
	short	y;

	struct my_model
	{
		char	modelname[40];
		int		modelid;
		double	size;
		long	a;
		short	b;
	};
} TSTRUCT;

void DumpStruct( TSTRUCT* data )
{
	printf( "name = '%s', id = %d, sal = %f, x = %d, y = %d\n", data->name, data->id, data->sal, data->x, data->y );
	printf( "modelname = '%s', modelid = %d, size = %f, a = %d, b = %d\n\n", data->modelname, data->modelid, data->size, data->a, data->b );
}

void TestStruct()
{
	TSTRUCT t1 = { 0 };
	TSTRUCT t2 = { "Struct1", 1, 0.25, 100, 80, "Model1", 1 };
	TSTRUCT t3, t4;
	memset( &t3, 0, sizeof( TSTRUCT ) );
	DumpStruct( &t1 );
	DumpStruct( &t2 );
	DumpStruct( &t3 );
	DumpStruct( &t4 );
}

Open in new window

The output looks somehow like this:
name = '', id = 0, sal = 0.000000, x = 0, y = 0
modelname = '', modelid = 0, size = 0.000000, a = 0, b = 0

name = 'Struct1', id = 1, sal = 0.250000, x = 100, y = 80
modelname = 'Model1', modelid = 1, size = 0.000000, a = 0, b = 0

name = '', id = 0, sal = 0.000000, x = 0, y = 0
modelname = '', modelid = 0, size = 0.000000, a = 0, b = 0

name = '-', id = 1967720243, sal = 0.000000, x = 3864780, y = -19707
modelname = '', modelid = 4, size = 0.000000, a = 4201248, b = 0

Open in new window

So only the last instance t4 has undefined values, so each of the other methods IMO lead to the wanted result.

@Kdo: You wrote
In the short example above, X.i1 gets initialized to zero, X.i2 does not get initialized.  Y.i1 and Y.i2 get initialized.

Note that X.i2 will be zero if the variable is create in the globals block (not within a function) as all items in the globals block default to zero.
I'm not able to reproduce this, as shown in the above sample even all members of t1 are set to Zero.

Do you know any spec about this? Maybe it differs between compilers?

Best regards,

ZOPPO
0
 
LVL 46

Expert Comment

by:Kent Olsen
ID: 39900252
Hi Zoppo,

My "memory" and habits go all the way back to before the C90 standards.  In modern compilers, (C99) initialization is a lot friendlier

From the Standard:

[6.7.8.21] If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.

So you're correct.  Static storage defaults to 0, so what you describe and test is exactly what the standard says it should be.

Thanks for keeping me honest (and smarter)!
Kent
0
 
LVL 31

Expert Comment

by:Zoppo
ID: 39900265
Hi Kdo,

thanks to you too for posting the appropriate standard here. To be honest searching/reading/finding specs is one of my weaknesses :-/

ZOPPO
0
 
LVL 46

Expert Comment

by:Kent Olsen
ID: 39900297
Thanks...  I certainly didn't remember that.  :)  Google search is our friend.  Sometimes....

I really should reread the entire standard.  An awful lot is different from the C90 standard and it's a completely different world from the pre-C90 days.  But then, I don't know how to read that much dry material and stay awake!  It's a tough read!!!

Kent
0
 
LVL 9

Expert Comment

by:Subrat (C++ windows/Linux)
ID: 39905346
@ID: 39899890:

TSTRUCT t1 = { 0 };
This initialization works during declaring if we are initializing members. But think about constructor. Inside class declaration we can't initialize a member.we have to do it in class defination and more appropriately in constructor. So inside constructor we can't write t1={};
It doesn't make any scence.
Utiately we have to use memset to do the initialization in a single shot. Else each member have to be initiaized separetely which is some what more unnecessary work.

TSTRUCT t1 = { 0 }; also can be written as TSTRUCT t1 = {  };
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article shows you how to optimize memory allocations in C++ using placement new. Applicable especially to usecases dealing with creation of large number of objects. A brief on problem: Lets take example problem for simplicity: - I have a G…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.

876 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question