Alter Mann Alter Mann - 3 months ago 16
C Question

Set value to 0 via pointer to char

I want to set the value of the (dereferenced) passed variable to

NULL
if it is a
const char *
and to
0
if it is a
double
, assuming that
NULL
is defined as
(void *)0
and
sizeof(const char *) == sizeof(double)
, is this code safe? is there a better approach to achieve the same?

If not, please, don't suggest to use
union
s, I am stuck with
void *
(building an interpreter) and I can not pass the type as parameter, I only need those 2 type (
const char *
and
double
).

#include <stdio.h>
#include <string.h>

static void set0(void *param)
{
if (sizeof(const char *) == sizeof(double)) {
*(const char **)param = 0;
}
}

int main(void)
{
const char *str = "Hello";
double num = 3.14;

printf("%s\n", str);
printf("%f\n", num);
set0(&str);
if (str != NULL) {
printf("%s\n", str);
}
set0(&num);
printf("%f\n", num);
return 0;
}

Answer

In order for this to be safe even on platforms where sizeof(double) is the same as sizeof(const char*) one other condition must be in place: the way the system represents doubles must interpret bits of a NULL pointer as 0.0.

Although this is true for many platforms, because both NULL and 0.0 are represented as sequences of zero bytes of identical length, the standard by no means requires this to be true. Zero double may have a representation different from what it is in IEEE-754. Similarly, NULL pointer is not required to be represented as a zero (although the compiler must ensure that zero comparison of NULL pointer succeeds). Therefore, you end up with rather unportable code.

Comments