0

我在 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;
}

我正在尝试以以下方式对其进行测试:

#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;
}

但是,我得到以下结果:

解析结果:Along 1 is 1234567890 Along 2 is 4294967295

为什么第二个 unsigned long 是错误的?

谢谢

4

2 回答 2

7

您提供的第二个整数太大而无法在架构的内存中表示。所以,根据它的 API,strtoul只是返回你 ULONG_MAX(在你的架构上=4294967295),同时将errno 设置ERANGE

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

但是,如果您给出较小的整数,它也可能会失败,因为strtoul仅在遇到非数字字符时才会停止解析。由于您没有确保这一点,因此您无法确定strtoul不会尝试解析您的字符串之后的内存中的任何内容。(所以假设随机,256 次中有 10 次出现转换错误)

用 \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';
于 2012-06-25T13:12:54.113 回答
0

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

于 2012-06-25T13:08:28.060 回答