开发者

The memset() function

I am a beginner to C/C++, and I came across the following segment of code:

#define MAX_MSG 1000
char *szBuf = new char[MAX_MSG];
char *szBufRaw = new char[MAX_MSG];
memset(szBuf, ‘\0’, strlen(szBuf));
memset(szBufRaw, ‘\0’, 开发者_如何学JAVAstrlen(szBufRaw));

I've read the tutorial about memset here:

http://www.java-samples.com/showtutorial.php?tutorialid=591

and I believe the above code is correct, but the original author of the code believes there is a bug within it, could anybody give me a hint? Thanks in advance.


strlen(szBuf)(and strlen(szBufRaw)) will return correct result only on valid strings. You should pass MAX_MSG instead.


strlen() looks for the first null value in the array, which means that you won't memset the right amount of bytes in memory.

Use MAX_MSG instead to set the entire array to null.


Both char arrays are uninitialized, the use of strlen() on them is undefined behavior. It will not do what you expect.

strlen() walks through a string, given the pointer to its first character, and return the length of the string, that is, until it finds the terminating zero. After you create these arrays with new, they don't contain anything meaningful. these calls may return anything, and may even crash your program.

What you want is to pass the size of the arrays:

memset(szBuf, ‘\0’, MAX_MSG);
memset(szBufRaw, ‘\0’, MAX_MSG);


strlen() returns the length of a string given.
The length is defined as the length between the head and the tail whose value is \0.

In the code above, strlen() will not necessarily returns MAX_MSG, because you haven't initialize or set some value yet.

memset(szBuf, ‘\0’, sizeof(szBuf))

will work.


strlen will not behave as you expect because it counts the number of bytes before a NUL (0 ascii code) char. What you need is to pass MAX_MSG instead of strlen. By the way, is this homework?


Before calling memset, the two buffers szBuf and szBufRaw are uninitialized. However, to get the length of memory to clear, the code calls strlen on them. That won't work because the buffers don't contain valid strings. The code should be clearing MAX_MSG bytes in the buffers instead of using strlen.


memset(szBuf, ‘\0’, strlen(szBuf));

Whats strlen() doing in there? Where are the strings?

The strlen() function returns the number of characters that precede the terminating null character in a C style string.

memset(szBuf, ‘\0’, MAX_MSG); should work.


Uninitialized memory allocated by new won't behave nice with strlen().

It'd be better if one wrote:

memset(szBuf, 0, MAX_MSG * sizeof *szBuf);

You could also skip sizeof *szBuf since it's guaranteed to be 1, but it doesn't hurt.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜