Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ new * char aren't empty

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 ?

like image 217
Kacper Fałat Avatar asked Jun 01 '13 11:06

Kacper Fałat


People also ask

How to test if a char is empty in C?

To check if a given string is empty or not, we can use the strlen() function in C. The strlen() function takes the string as an argument and returns the total number of characters in a given string, so if that function returns 0 then the given string is empty else it is not empty.

How do I check if a char is empty?

C++ isblank() The isblank() function in C++ checks if the given character is a blank character or not.

How do you set a null character in C++?

You can use c[i]= '\0' or simply c[i] = (char) 0 . The null/empty char is simply a value of zero, but can also be represented as a character with an escaped zero.

What character is \0 in C++?

It's the null character, and its ASCII name is NUL.


2 Answers

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

like image 95
Mike Vine Avatar answered Oct 04 '22 22:10

Mike Vine


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
                             ^^
like image 36
juanchopanza Avatar answered Oct 04 '22 20:10

juanchopanza