NO

Author Topic: Strange behavior with strncpy when value is exactly 288000  (Read 81 times)

Offline xultz

  • Member
  • *
  • Posts: 1
Strange behavior with strncpy when value is exactly 288000
« on: November 06, 2017, 06:30:54 pm »
Hi, I'm working with some bytes, and I need to access the bytes from int variables. I do a strncpy of the bytes to a buffer, and it works well... except if the value is exactly 288000.
The following program shows a test I did:

Code: [Select]
#include <stdio.h>
#include <string.h>

int main(int argc, char ** argv)
{
unsigned int x;
unsigned char buffer[10];

printf("Pelles C test\n");

x = 287998;
strncpy((char *)buffer, (char *)&x, 4);
printf("%d:%02X %02X %02X %02X\n", x, buffer[3], buffer[2], buffer[1], buffer[0]);

x = 287999;
strncpy((char *)buffer, (char *)&x, 4);
printf("%d:%02X %02X %02X %02X\n", x, buffer[3], buffer[2], buffer[1], buffer[0]);

x = 288000;
strncpy((char *)buffer, (char *)&x, 4);
printf("%d:%02X %02X %02X %02X\n", x, buffer[3], buffer[2], buffer[1], buffer[0]);

x = 288001;
strncpy((char *)buffer, (char *)&x, 4);
printf("%d:%02X %02X %02X %02X\n", x, buffer[3], buffer[2], buffer[1], buffer[0]);

x = 288002;
strncpy((char *)buffer, (char *)&x, 4);
printf("%d:%02X %02X %02X %02X\n", x, buffer[3], buffer[2], buffer[1], buffer[0]);

x = 288003;
strncpy((char *)buffer, (char *)&x, 4);
printf("%d:%02X %02X %02X %02X\n", x, buffer[3], buffer[2], buffer[1], buffer[0]);

return 0;
}

That code gives me the following output:

Code: [Select]
Pelles C test
287998:00 04 64 FE
287999:00 04 64 FF
288000:00 00 00 00
288001:00 04 65 01
288002:00 04 65 02
288003:00 04 65 03

As can be seen above, all values give me the correct bytes, except for 288000, which gives me zeros. I tried some other random values, and I got good results. The only problem is with 288000.

I'm using Pelles 8.00.60 (Win64)

Offline Robert

  • Member
  • *
  • Posts: 182
Re: Strange behavior with strncpy when value is exactly 288000
« Reply #1 on: November 06, 2017, 07:27:25 pm »
Interesting.

I get the same output as you on exes compiled using the Windows MinGW and Microsoft compilers and, as well, the g++ compiler on Linux.

Offline TimoVJL

  • Global Moderator
  • Member
  • *****
  • Posts: 1628
Re: Strange behavior with strncpy when value is exactly 288000
« Reply #2 on: November 06, 2017, 09:14:55 pm »
Not a bug.
Function strncpy() is not suitable for binary values.
Code: [Select]
#include <stdio.h>
#include <string.h>

int main(void)
{
unsigned int x;
unsigned char buffer[10];

printf("Pelles C test\n");

for (x = 287998; x < 288003; x++)
{
// strncpy((char *)buffer, (char *)&x, 4);
memcpy((char *)buffer, (char *)&x, 4);
printf("%d:%02X %02X %02X %02X\n", x, buffer[3], buffer[2], buffer[1], buffer[0]);
}
return 0;
}
May the source be with you