 Jorge Lopez Jr -3 years ago 113
C Question

# C - keep running into an infinite loop

I'm running into a problem with the following loop. The idea is to loop through a string and grab every two values (hex specifically), then store that value into an array. The string would then decrement in length by 2 because the two values will not be included in the next iteration.

The problem I keep running into is that the last two characters of the string keep being added to every new copy. The first copy would be okay, then the second copy would have the last two chars appended to the string (so two copies of the last two elements would be at the end of the string), then the third would have the values appended again and it never stops.

Is there something I'm missing here? Is there possibly a better approach to this problem?

`````` PC = d; //assign counter the value of the address
unsigned int c;
char copy; //copy of instruction set

int i = 0;

while (strlen(value) > 0) {
sscanf(value,"%2x",&c); //get every two hex chars from string and that value to c
allocMem[d+i] = (char) c; //put value of c in array
strncpy(copy,value+2,strlen(value)-2); //get a copy of new value of the string
strcpy(value,copy); //copy new value to value variable
i += 2;

d++;
}
`````` Weather Vane
Answer Source

The function `strncpy` will not nul-terminate the new string, since it reached the length limit given before finding a terminator. So when you `strcpy` back to the original string, you are not passing a string to `strcpy` but an unterminated array.

To include the terminator you would have to make the copy length one longer than `strlen(value)-2` with

``````strncpy(copy, value+2, strlen(value) - 1);
``````

Or, to save messing around with copying to and fro, you could simplify it by using a pointer instead, such as in this example:

``````#include <stdio.h>

int main(void){
char value[] = "abcdef";
char *ptr = value;
unsigned c;
while(sscanf(ptr, "%2x", &c) == 1) {
printf("%X\n", c);
ptr += 2;
}
}
``````

Program output

``````AB
CD
EF
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download
Latest added