开发者

Cannot understand how new or malloc does work with BYTE*

I开发者_StackOverflow trying to allocate memory for 10 bytes

BYTE* tmp;
tmp = new BYTE[10];
//or tmp = (BYTE*)malloc(10*sizeof(BYTE));

But after new or malloc operation length of *tmp more than 10 (i.e. '\0' char not in 10 position in tmp array)

Why?


Neither new[] nor malloc() will place the \0 for you. When you call malloc() or new[] for char the block is unitilialized - you need to initialize it manually - either put \0 into the last element, or use memset() for the entire block.


There is no reason for '\0' to be at the end of the array.

malloc (or new, for that matter), gives you back a block of 10 bytes, which is memory it allocated for you. It's your job to do whatever you want with this memory.

You're probably getting mixed up with a string (like char[10], for example).

The whole idea of a string is to be an array of bytes, but which ends with '\0' to denote its size.

An array of bytes, or any other array you allocate which isn't a string, won't neceassrily end with '\0'; it's your job to keep track of its size.


First, BYTE array can contains zeros, thats why you can't use strlen to determine array length.

Second, after calling new BYTE[10] your arrray remains uninitalized (contains garbage) if you want automaticly initalize array with 0 you can use the following code:

BYTE* tmp2;
tmp2 = new BYTE[10]();

But even in this case you can't use strlen, because strlen returns 0.

You must save array length into some variable or simply use std::vector instead.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜