Sign in to follow this  

problems with memset

This topic is 1757 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Here's the code:

 

class gg{
public:
	char ce[10];
	gg(char j = ' ') { memset(ce,j,sizeof(ce));};
};
int main() {
	gg x('m');
	cout << x.ce << endl;

    
}

 

 

It outputs all those 10 ms,and then a series of weird symbols appear,why does that happen?

Share this post


Link to post
Share on other sites

Your string is not null terminated and so the stream is printing whatever follows the last element until the first null character. Add a '\0' at the end to mark the end of the string.

Share this post


Link to post
Share on other sites

Uh, no. He's about to overwrite the 10 chars in ce with 10 'm' characters so making it the empty string before you do that isn't very useful.

 

You need to do this

 

memset(ce, j, sizeof(ce) - 1);

ce[sizeof(ce)-1] = '\0';

 

You'll want to up the array size to 11 if you want to store 10 'm' characters in the array though as well as the null terminator.

 

Note: this only works since sizeof char is defined as 1.

Share this post


Link to post
Share on other sites

Note: this only works since sizeof char is defined as 1.

You can solve this by using sizeof(char):

 

memset(ce, j, sizeof(ce) - sizeof(char));

 

However, unless I'm very mistaken, sizeof(char) is guaranteed to be 1.

 

Only if the char array is previously initialized to zero, which I believe is not the case for local variables (their value, and, for pointers, the memory they point to, is undefined).

 

EDIT: never mind that. And, yes, sizeof(char) is defined to be 1 by the C and C++ standard. Don't have the references with me now, though. Of course it's best to get in the habit of using vectors (and strings) if using C++, there's no overhead and it's just simpler and safer to use, not to mention more idiomatic.

Edited by Bacterius

Share this post


Link to post
Share on other sites
Sign in to follow this