Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to memset bool to 0?

Suppose I have some legacy code which cannot be changed unless a bug is discovered, and it contains this code:

bool data[32]; memset(data, 0, sizeof(data)); 

Is this a safe way to set all bool in the array to a false value?

More generally, is it safe to memset a bool to 0 in order to make its value false?

Is it guaranteed to work on all compilers? Or do I to request a fix?

like image 205
Neil Kirk Avatar asked Oct 28 '15 00:10

Neil Kirk


People also ask

Why does memset only work 0 and 1?

memset allows you to fill individual bytes as memory and you are trying to set integer values (maybe 4 or more bytes.) Your approach will only work on the number 0 and -1 as these are both represented in binary as 00000000 or 11111111 . Show activity on this post. Because memset works on byte and set every byte to 1.

Does memset work with long long?

memset only uses one byte of the value passed in and does bytewise initialization. If you want to initialize a long long array with a particular value, just use std::fill or std::fill_n and let your library and compiler optimize it as they can (partial loop unrolling etc).

Is bool more efficient than int?

Using a bool IMO reflects its use much better than using an int . In fact, before C++ and C99, C89 didn't have a Boolean type. Programmers would often typedef int Bool in order to make it clear that they were using a boolean.

Why do we need memset?

memset() is used to fill a block of memory with a particular value. The syntax of memset() function is as follows : // ptr ==> Starting address of memory to be filled // x ==> Value to be filled // n ==> Number of bytes to be filled starting // from ptr to be filled void *memset(void *ptr, int x, size_t n);


1 Answers

Is it guaranteed by the law? No.

C++ says nothing about the representation of bool values.

Is it guaranteed by practical reality? Yes.

I mean, if you wish to find a C++ implementation that does not represent boolean false as a sequence of zeroes, I shall wish you luck. Given that false must implicitly convert to 0, and true must implicitly convert to 1, and 0 must implicitly convert to false, and non-0 must implicitly convert to true … well, you'd be silly to implement it any other way.

Whether that means it's "safe" is for you to decide.

I don't usually say this, but if I were in your situation I would be happy to let this slide. If you're really concerned, you can add a test executable to your distributable to validate the precondition on each target platform before installing the real project.

like image 155
Lightness Races in Orbit Avatar answered Oct 16 '22 04:10

Lightness Races in Orbit