简体   繁体   English

使用memcpy和strtoul获得乱码而不是数字

[英]Getting gibberish instead of numbers using memcpy and strtoul

I have the following piece of code compiling under gcc: 我在gcc下编译了以下代码:

int parseMsg(const char *msg_to_parse, unsigned long *exp_input, unsigned long *sysTicks )
{
   int l_msg_size = strlen(msg_to_parse);
   if(l_msg_size <10)
          return -1;
    char l_exp_input_arr[10];
    char l_sys_ticks_arr[10];
    memcpy(l_sys_ticks_arr,msg_to_parse+12,10);

    memcpy(l_exp_input_arr,msg_to_parse,10);
   //l_msg_size = strlen(msg_to_parse);
    *sysTicks = strtoul(l_sys_ticks_arr,NULL,10);

   *exp_input = strtoul(l_exp_input_arr,NULL,10);



   return 0;
}

And I'm trying to test it in the following manner: 我正在尝试通过以下方式对其进行测试:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int parseMsg(const char *msg_to_parse, unsigned long *exp_input, unsigned long *sysTicks );

int main(void) {
char msg[] = "1234567890  59876543213";
unsigned long along1, along2;
along1 =0;
along2=0;
parseMsg(msg,&along1, &along2 );
printf("result of parsing: \n \t Along 1 is %lu \n \t Along 2 is %lu \n",along1, along2);
return 0;
}

But, I'm getting the following result: 但是,我得到以下结果:

result of parsing: Along 1 is 1234567890 Along 2 is 4294967295 解析结果:沿1为1234567890沿2为4294967295

Why is the second unsigned long wrong? 为什么第二个unsigned long错误?

Thanks 谢谢

The second integer you provide is too big to be represented in memory on your architecture. 您提供的第二个整数太大,无法在体系结构的内存中表示。 So, according to its API, strtoul is just returning you ULONG_MAX (=4294967295 on your architecture), along with setting errno to ERANGE 因此,根据其API, strtoul只会返回ULONG_MAX(在您的体系结构上= 4294967295), 并将 errno设置ERANGE

strtoul API is here : http://www.cplusplus.com/reference/clibrary/cstdlib/strtoul/ strtoul API在这里: http ://www.cplusplus.com/reference/clibrary/cstdlib/strtoul/

BUT it may also fail if you gave a smaller integer, because strtoul only stops parsing when it encounters a non-numerical character. 但是 ,如果您提供较小的整数,它也可能会失败,因为strtoul仅在遇到非数字字符时才停止解析。 Since you didn't ensure that, you cannot be sure that strtoul will not try to parse whatever is in memory just after your strings. 由于您不能确保这样做,因此无法确定strtoul在字符串之后不会尝试解析内存中的任何内容。 (So assuming random, you have 10 chance out of 256 to have a conversion error) (因此,假设是随机的,则您有256个错误中有10个出现转换错误的机会)

Terminate your strings with \\0, it will be ok then : 用\\ 0终止字符串,然后可以:

char l_exp_input_arr[11]; // +1 for \0
char l_sys_ticks_arr[11];

memcpy(l_sys_ticks_arr, msg_to_parse+12, 10);
l_sys_ticks_arr[10] = '\0';

memcpy(l_exp_input_arr, msg_to_parse, 10);
l_exp_input_arr[10] = '\0';

您需要使两个临时char []变量长一个char,然后使最后一个字符为NULL。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM