简体   繁体   中英

sprintf stack buffer overflow

I'm trying to store a string in a char variable using sprintf. The code compiles, but when I run it I get a stack buffer overflow error. My compiler gives me information about why there was an error, but I can't tell what is actually wrong.

int numbers[] is an array with length 6, and matchHighest is an integer = 0.

I called match6 in this function:

int match(int numbers[], int matchHighest){
    int matchArray[] = {0, 0, 0, 0, 0};
    int i = 0;
    char m6[100] = "";
    char *m6p = m6;
    match6(&numbers[i], matchArray, &m6[100]);   

Here is where the error is occuring:

int match6 (int numbers[], int matchArray[5], char *m6){
    int i=0;
    while((numbers[i]==numbers[i+1]) && (i<5)){
        i++;
    }
    if(i == 5){
        matchArray[4] = 6 * numbers[0] + 27;
        sprintf(m6, "Rule match-6(%d) - score %d", numbers[0], matchArray[4]);
        printf("%s\n", m6);
    }
    return matchArray[4];
}

When it runs, I get this error (all the values at the bottom are correct and as expected):

draft6.c:98 runtime error - stack buffer overflow

dcc explanation: access past the end of a local variable. Make sure the size of your array is correct. Make sure your array indices are correct.

Execution stopped here in match6(4) - score 51") in draft6.c at line 98:

if(i == 5){
    matchArray[4] = 6 * numbers[0] + 27;
-->     sprintf(m6, "Rule match-6(%d) - score %d", numbers[0], matchArray[4]);
    printf("%s\n", m6);
}

Values when execution stopped:

i = 5
m6 = "Rule match-6(4) - score 51"
matchArray[4] = 51
numbers[0] = 4

match6(&numbers[i], matchArray, &m6[100]); . You pass the address of the item beyond the last allocated item. After which match6 writes out of bounds. Instead of doing strange things, simply pass the array:

char m6[100] = "";
match6(&numbers[i], matchArray, m6);  

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