Dark Bit Factory & Gravity

PROGRAMMING => C / C++ /C# => Topic started by: Stonemonkey on January 27, 2008

Title: Clearing allocated memory when using New
Post by: Stonemonkey on January 27, 2008
This is causing me a few headaches atm, is there any way to have the memory allocated with New cleared?
Title: Re: Clearing allocated memory when using New
Post by: Jim on January 27, 2008
No, you'd need to call memset. eg,
Code: [Select]
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
Title: Re: Clearing allocated memory when using New
Post by: Stonemonkey on January 27, 2008
Ah ok Jim, that's a bit of a pain but thanks.
Title: Re: Clearing allocated memory when using New
Post by: Stonemonkey on January 27, 2008
Code: [Select]

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.
Title: Re: Clearing allocated memory when using New
Post by: Jim on January 28, 2008
Some compilers will let you have
Code: [Select]
#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
Code: [Select]
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
Title: Re: Clearing allocated memory when using New
Post by: Stonemonkey on January 28, 2008
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.