Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The memset() function

Tags:

c++

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’, strlen(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.

like image 698
Kevin Avatar asked Jun 12 '26 09:06

Kevin


2 Answers

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

like image 91
Kirill V. Lyadvinsky Avatar answered Jun 14 '26 23:06

Kirill V. Lyadvinsky


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.

like image 40
Stefan H Singer Avatar answered Jun 14 '26 22:06

Stefan H Singer