1

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
4
  • How are you calling match6? It can be that while((numbers[i]==numbers[i+1]) && (i<5)){ you are accessing numbers[5] here. Commented Mar 25, 2019 at 9:20
  • See the exact invocation of match6 would be nice. Along with the declarations of the things you pass in as paramaeters. Commented Mar 25, 2019 at 9:21
  • Have you allocated memory in any way for char *m6 ? Commented Mar 25, 2019 at 9:27
  • I edited my post. If you need more info let me know Commented Mar 25, 2019 at 9:28

1 Answer 1

3

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);  
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.