Malloc ; memset ; new

hi guys,
what essentially is the difference between Malloc, Memset and new..


is it true that memory allocation with malloc/memset doesnt invoke constructor?
Yes, and that is the main difference. Don't use malloc with any non-POD types.

malloc also returns a void* (it doesn't know what type you want), but new will return the correct pointer type, so:

int* my_ptr = new double; //gives an error
memset() doesn't allocate memory. It's used to set memory to byte values (usually zero). For example, this is a very common way of calling it:
memset(a,0,sizeof(a));
This sets all bytes of a to zero, regardless of the type of a. I can't stress enough that it sets bytes, not elements.
@ helios
Yeah, i did a lill come work to understand what you meant..

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include<iostream>

class someClass
{
	char* greeting;

public:
	someClass()
	{
		greeting="hello.. Welcome to C++ World";
	}

	void greet()
	{
		std::cout<<greeting;
	}
};

int main(int argc,char* argv[])
{
	someClass class1;
	class1.greet();
	
	someClass* memSetGreeter=NULL;
	memset(memSetGreeter,0,sizeof(someClass));
	memSetGreeter->greet();
}


but memset throws an exception... whats the problem??

And when you meant, it allocates bytes and sets it value to all zeros, does that meant that memSetGreeter->greet would fail???
Yes, because memSetGreet is pointing at NULL. You can't modify NULL, so when you try to memset it, you get a seg fault.
And when you meant, it allocates bytes and sets it value to all zeros
I said it doesn't allocate anything.

EDIT: Sorry, I made a mistake earlier. That's supposed to be
memset(&a,0,sizeof(a));
Last edited on
Ok.. So means that we cannot instantiate an object with the help of memset ??

Yes. You need to use malloc() or new to actually make an object.
Actually what you have tried to implement doesn't make sense.
To use memset you need to allocate some memory using new or malloc.

memset is used to copy characters to some buffer(int array, char array, byte array etc.) not to assign 0 to class object( u have used class object here)

After allocating memory for memSetGreeter using new if you write the code below
memset(memSetGreeter,0,sizeof(someClass));
you will loose the pointer you got by "new"ing

i hope following example may help you to understand memset
1
2
3
4
5
6
7
8
9
10
11
12
void memsetsample()
{
    char* pch = new char[10];
    memset( pch, 'A', 10 );

    int* pn = new int[10];
    memset( pn, 0, sizeof(int)*10 );
    for( int nCount = 0; nCount < 10; nCount++ )
    {
        cout<<pch[nCount]<<" "<<pn[nCount]<<"\n";
    }
}


will produce the following output
A 0
A 0
A 0
A 0
A 0
A 0
A 0
A 0
A 0
A 0

Last edited on
Reannah wrote:
To use memset you need to allocate some memory using new or malloc.

That's not correct. You can use it to initialize a stack allocated array or POD struct:

1
2
int a[2000];
memset(&a, 0, sizeof(a));
@filipe: memset() is only initializing the array. The allocation occurred on the stack when you declared it, not when you used memory. memset() works only on memory you already have; it doesn't get you memory.
@Zhuge: as I said,

You can use it to initialize a stack allocated array or POD struct
Apologies, I misread Reannah's post.
i said "To use memset you need to allocate some memory using new or malloc". i meant in this particular case. since Karthick22 was discussing about new, malloc and memset. He has declared a poinetr object. i just continued from there.
Pardon me, I thought you meant it generally.
@all..
u guys have made this thread a superb reference..

@ Reannah
u got everything u said but not "you loose pointer you got after newing".. is it because new adds some kind of header info to maintain the state of the object??

Or in other words.. how ll the object look like in memorY??
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include<iostream>

class someClass
{
	char* greeting;

public:
	someClass()
	{
		greeting="hello.. Welcome to C++ World";
	}

	void greet()
	{
		std::cout<<greeting;
	}
};

int main(int argc,char* argv[])
{
	someClass class1;
	class1.greet();
	
	someClass* memSetGreeter=NULL;
	memset(memSetGreeter,0,sizeof(someClass));
	memSetGreeter->greet();
}


Even if you allocate the memory, memset still doesn't make sense in this example. You'd simply be resetting the pointer to NULL and greet() would print nothing. That wouldn't be a valid use of memset and you also shouldn't use memset on non-POD types. Use the constructors and interface functions of the class instead.

To fill an array of integers with zero use std::fill.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
void memsetsample()
{
    char* pch = new char[10];
    memset( pch, 'A', 10 );

    int* pn = new int[10];
   // memset works but not as intuitive as std::fill and much more error prone.  Also it only works with
   // zero.
   // memset( pn, 0, sizeof(int)*10 );  
   // see how much easier that is?  Don't need to calculate the size in bytes.  Just specify the number of elements.
    std::fill(pn, pn + 10, 0); 
    for( int nCount = 0; nCount < 10; nCount++ )
    {
        cout<<pch[nCount]<<" "<<pn[nCount]<<"\n";
    }
    // use std::generate if you have a predicate function to pick values.  In this case, I use rand from
    // the C library
    std::generate(pn, pn + 10, rand); 
    for( int nCount = 0; nCount < 10; nCount++ )
    {
        cout<<pch[nCount]<<" "<<pn[nCount]<<"\n";
    }
}
But that doesn't overwrite the pointer. memset(&memSetGreeter,0,sizeof(memSetGreeter)); does. What he's doing in that example is merely an illegal write.

greet() would print nothing
No, the program would crash when trying to do ((const char *)0)[0].
Topic archived. No new replies allowed.