Home > Software design >  memset with math class macros
memset with math class macros

Time:05-21

I am trying to use memset with INFINITY or NAN present in C header file <math.h> My code is:

double *dist;
dist = (double *)malloc(7*sizeof(double));
memset(dist, INFINITY, 7*sizeof(dist[0]));

However, on execution it gives me the following errors:

main.c:10:18: warning: overflow in conversion from ‘float’ to ‘int’ changes value from ‘ Inff’ to ‘2147483647’ [-Woverflow]
   11 |     memset(dist, INFINITY, 7*sizeof(dist[0]));

But I know INFINITY and NAN is represented using float. So why is it giving me an error? I even tried by using float instead of double but same issue. But, with any other floating point values it is working perfectly. Please help.

P.S.: It works perfectly fine if I use a loop instead of memset.

Edit: Is there any other way of doing this by avoiding the loop?

CodePudding user response:

As mentioned in other answers, the memset is not going to work because it fills the data with a single byte pattern. In the single precision floating point standard 754, the "infinity" is be encoded as 00 00 80 7f bytes (assuming little endian). Therefore it is not possible to use memset for desired initialization. Frankly, it's difficult to use this function for initialization with anything other than zeros or all-one bits.

However, if you use GCC, CLANG or ICC then there is an extensions allowing specify ranges in designated initializers:

float arr[] = { [0 ... 6] = INFINITY };

The either use arr as dist or copy it with memcpy.

memcpy(dist, arr, sizeof arr);

The compiler may be smart enough to optimize this operation.

The operation can be "one-lined" with a help of compound initializer.

memcpy(dist, (float[]){ [0 ... 6] = INFINITY }, 7 * sizeof *dist);

CodePudding user response:

memset sets each byte to a given byte value. A double is bigger than a byte so one cannot use memset to set a double buffer to INFINITY. The best way to accomplish this is via a loop.

for (int i = 0; i < 7;   i)
    dist[i] = INFINITY;
  • Related