9

I had one question.

I developing server in ASIO and packets are in pointed char.

When i create new char (ex. char * buffer = new char[128];) i must clean it manually to nulls.

By:

for(int i =0;i<128;i++)
{
buffer[i] = 0x00;
}

I doing something wrong, that char isn't clear ?

Kacper Fałat
  • 633
  • 3
  • 9
  • 17
  • Your question is already answered by [Do the parentheses after the type name make a difference with new?](http://stackoverflow.com/questions/620137/do-the-parentheses-after-the-type-name-make-a-difference-with-new). – Troubadour Jun 01 '13 at 11:31

4 Answers4

22

You do not have to loop over an array of un-initialized values. You can dynamically instantiate array of zeros like this:

char * buffer = new char[128](); // all elements set to 0
                             ^^
juanchopanza
  • 223,364
  • 34
  • 402
  • 480
14

There are two types of ways of calling the new operator in C++ - default initialised and zero initialised.

To default initialise (which will leave the value undefined) call:

int * i = new int;

It is then undefined behavoir to read or use this value until its been set.

To zeroinitialise (which will set to 0) use:

int * i = new int();

This also works with arrays:

int * i = new int[4]; // ints are not initialised, you must write to them before reading them
int * i = new int[4](); // ints all zero initialised

There's some more info here

Community
  • 1
  • 1
Mike Vine
  • 9,468
  • 25
  • 44
3

Allocated memory will not be clear, it will contain random stuff instead. That's how memory allocation works. You have to either run a for-loop or use memset to clear it manually.

kirelagin
  • 13,248
  • 2
  • 42
  • 57
2

You also can use calloc. It initializes each elem to 0 automaticaly. e.g:

 char* buffer = (char *) calloc (128, sizeof (char))

First param is number of blocks to be allocated. Second is size of block. This function returns void* so you have to convert its value to (char *) If you use calloc (or malloc or any "pure c" allocation functions) you'd better use free function to deallocate memory instead of delete.

user2422869
  • 750
  • 7
  • 17