c - segfault when using strtok_r -


i want split string in c code:

char *search = "+" ; char *temp1; char *temp2; char *saveptr1, *saveptr2 ; int operand1 ; int operand2 ; int result ; char sumbuff [5][25]     temp1 = strtok_r(sumbuff[sumcounter-1], search, &saveptr1) ; operand2 = atoi(strtok_r(null, search, &saveptr1)); temp2 = strtok_r(temp1, ".", &saveptr2) ; operand1 = atoi(strtok_r(null, ".", &saveptr2)) ; 

but when run in main code segmentation fault. , trace stack result:

#0  0x00007ffff7834517 in ?? () /lib/x86_64-linux-gnu/libc.so.6 #1  0x00007ffff7830f60 in atoi () /lib/x86_64-linux-gnu/libc.so.6 #2  0x000000000040108c in plusexec (arg=0x0) @ cm.c:112 #3  0x00007ffff7bc4182 in start_thread () /lib/x86_64-linux-gnu/libpthread.so.0 #4  0x00007ffff78f147d in clone () /lib/x86_64-linux-gnu/libc.so.6 

cm.112 operand2 = atoi(...) how can correct error?

you not check return of strtok_r, can null , therefore crash atoi.

and in case:

temp2 = strtok_r(temp1, ".", &saveptr2) ; operand1 = atoi(strtok_r(null, ".", &saveptr2)) ; 

...you seem looking two consecutive points? such 5.123.723? if there one, atoi receive null , coredump.

if there shouldn't 2 consecutive "."'s, that's bug.

supposing not, try:

temp2 = strtok_r(temp1, ".", &saveptr2); // e.g. 5  // if there no other token, operand1 set zero. operand1 = 0; if (temp2 != null) {     char *temp3;     temp3 = strtok_r(null, ".", &saveptr2); // e.g. 123, or null     if (temp3 != null) {         operand1 = atoi(temp3);     } } 

(same approach first atoi).

depending on data format, might perhaps employ parser function return array of integers , cardinality; again, if need deal variably-dotted quantities, such 192.168.1.1 or 1.2.7.0.80.17 - otherwise needn't bother:

/**  * parses string in format 1.2343.293.777  * @param char * inputstring       input string  * @param int * vect               vector store integers  * @param size_t n                 maximum vector size  * @return size_t                  number of integers returned  */  size_t parsedottedintegers(char *inputstring, int *vect, size_t n) {     size_t = 0;     char *p;     char *save = null;     p = strtok_r(inputstring, ".", &save);     while (i < n) {         vect[i++] = atoi(p);         p = strtok_r(null, ".", &save);         if (null == p) {             return i;         }     }     // error (e.g. many parts)     return 0; } 

Comments

Popular posts from this blog

PHP DOM loadHTML() method unusual warning -

python - How to create jsonb index using GIN on SQLAlchemy? -

c# - TransactionScope not rolling back although no complete() is called -