sprintf堆栈缓冲区溢出

问题描述 投票:1回答:1

我正在尝试使用sprintf将字符串存储在char变量中。代码编译,但是当我运行它时,我得到一个堆栈缓冲区溢出错误。我的编译器向我提供了有关错误原因的信息,但我无法确定实际上是什么错误。

int numbers []是一个长度为6的数组,matchHighest是一个整数= 0。

我在这个函数中调用了match6:

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]);   

这是发生错误的地方:

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];
}

当它运行时,我收到此错误(底部的所有值都是正确的并且符合预期):

draft6.c:98运行时错误 - 堆栈缓冲区溢出

dcc说明:访问过去的局部变量的结尾。确保阵列的大小正确。确保您的数组索引正确。

执行在match6(4)中停止 - 在draft6.c中第98行得分51“):

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);
}

执行停止时的值:

i = 5
m6 = "Rule match-6(4) - score 51"
matchArray[4] = 51
numbers[0] = 4
c
1个回答
3
投票

match6(&numbers[i], matchArray, &m6[100]);。您将项目的地址传递到最后分配的项目之外。之后match6写出界限。不要做奇怪的事情,只需传递数组:

char m6[100] = "";
match6(&numbers[i], matchArray, m6);  
© www.soinside.com 2019 - 2024. All rights reserved.