Quantcast
Channel: Active questions tagged gcc - Stack Overflow
Viewing all articles
Browse latest Browse all 22088

sscanf() causing infinite loop by changing the index value of for loop

$
0
0

Function:

void input_bytes(unsigned char bytes[], int num_bytes){    const int CHAR_PER_BYTE = 2; /* expects hex input */    const int STRING_SIZE = num_bytes * CHAR_PER_BYTE;    char input_string[STRING_SIZE + 1];  /* + 1 for null char */    int ind;    unsigned char byte;    fgets(input_string, STRING_SIZE + 1, stdin);    printf("after fgets\n");    for (ind = 0; ind < num_bytes; ind++)    {        printf("top of loop, ind: %d\n", ind);        sscanf(input_string, "%2x", &byte);        bytes[ind] = byte;        printf("bottom of loop, ind: %d\n", ind);    }    printf("\n\n");}

Driver:

int main(){    unsigned char bytes[5];    input_bytes(bytes, 5);}

Output:

after fgetstop of loop, ind: 0bottom of loop, ind: 0top of loop, ind: 1bottom of loop, ind: 0top of loop, ind: 1bottom of loop, ind: 0top of loop, ind: 1bottom of loop, ind: 0top of loop, ind: 1bottom of loop, ind: 0top of loop, ind: 1bottom of loop, ind: 0top of loop, ind: 1bottom of loop, ind: 0top of loop, ind: 1bottom of loop, ind: 0top of loop, ind: 1bottom of loop, ind: 0...

Compiling with gcc driver.c -o driver.

I put an ind++ in the loop out of curiosity and it goes to 2 at the top and 1 at the bottom. If I take the sscanf() out it terminates.


Viewing all articles
Browse latest Browse all 22088

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>