C language > Beginner questions
Strange behavior with strncpy when value is exactly 288000
(1/1)
xultz:
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: ---#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;
}
--- End code ---
That code gives me the following output:
--- Code: ---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
--- End code ---
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)
Robert:
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.
TimoVJL:
Not a bug.
Function strncpy() is not suitable for binary values.
--- Code: ---#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;
}
--- End code ---
Navigation
[0] Message Index
Go to full version