• Welcome to Dark Bit Factory & Gravity.
 

Clearing allocated memory when using New

Started by Stonemonkey, January 26, 2008

Previous topic - Next topic

0 Members and 0 Guests are viewing this topic.

Stonemonkey

This is causing me a few headaches atm, is there any way to have the memory allocated with New cleared?

Jim

No, you'd need to call memset. eg,

Type *ptr = new Type[THING_COUNT];
memset((void *)ptr, 0, THING_COUNT * sizeof *ptr);


In C you can use calloc, but that's normally implemented as malloc/memset.

Jim
Challenge Trophies Won:

Stonemonkey

Ah ok Jim, that's a bit of a pain but thanks.

Stonemonkey

#3


char *my_new(int bytes)
{
char *new_mem=new char[bytes];
memset (new_mem,0,bytes);
return new_mem;
}

#define _new(type,num_elements) (type*)my_new(sizeof(type)*(num_elements))



would be nicer if I didn't have to specify 1 for a single element though.

EDIT: changed to use New.

Jim

Some compilers will let you have

#define _new(type,num_elements) (type*)my_new(sizeof(type)*(num_elements))
#define _new(type) (type*)my_new(sizeof(type))

defined at the same time and pick the right one depending how many parameters you pass.

I'd be tempted to write the function like this, but them I'm extremely pedantic

void *my_new(size_t bytes)
{
void *new_mem=(void *)new unsigned char[bytes];
memset(new_mem,0,bytes);
return new_mem;
}

#define _new(type,num_elements) (type*)my_new(sizeof(type) * (num_elements))


The reasons being that void * is the natural type for pointers that we don't know. unsigned char is a better choice than char for the allocation (char can be signed or unsigned, depending on compiler - it makes no difference in this case, but in general, use either 'signed char' or 'unsigned char' unless you're doing stuff with strings).  size_t is the correct type for 'bytes', it's unsigned, but might also be more than 32bits in size.
I'm pretty sure your sample won't compile because memset takes a void * as its first argument and you're passing it char *.  That's an error in C++, but not in C.

Jim
Challenge Trophies Won:

Stonemonkey

Ah right, initially I did use void* but decided to change it as I was allocating a number of bytes and It gave no errors or warnings.

Also, I did try the 2 defines but it just replaced the first with the second and gave a warning.

Thanks for that.