简体   繁体   中英

Getting gibberish instead of numbers using memcpy and strtoul

I have the following piece of code compiling under 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

Why is the second unsigned long wrong?

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

strtoul API is here : 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. 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. (So assuming random, you have 10 chance out of 256 to have a conversion error)

Terminate your strings with \\0, it will be ok then :

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。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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