Solved

Memset 0 or 0x00 ?

Posted on 2014-02-26
12
1,312 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 45

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
Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

 
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 45

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 500 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 45

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 45

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

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

IntroductionThis article is the second in a three part article series on the Visual Studio 2008 Debugger.  It provides tips in setting and using breakpoints. If not familiar with this debugger, you can find a basic introduction in the EE article loc…
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 goal of this video is to provide viewers with basic examples to understand how to use strings and some functions related to them in the C programming language.
The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…

820 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