C语言 分配的数组中的堆缓冲区溢出



所以我有这个程序,它有一个结构和一个数组。该数组是conj_jogos,它是一个名为jogo的结构数组,MAX_SIZE(MAX_SIZE为5(。

结构:

typedef struct
{
int id;
char equipas[2][1024];
int pont[2];
char nome[MAX_CHARS];
} jogo;

因此,为了创建这个数组,我在主函数中分配了内存,如下所示:

int main()
{
char nome_jg[MAX_CHARS], team1[MAX_CHARS], team2[MAX_CHARS];
int score1;
int score2;
int i;
conj_jogos = (jogo*)calloc(MAX_SIZE,sizeof(jogo));
while ((c = getchar()) != x)
scanf("%1023[^:n]:%1023[^:n]:%1023[^:n]:%d:%d",nome_jg,team1,team2,&score1,&score2);
remove_esp(nome_jg); /*removes the 1st char if its a space*/
a(nome_jg,team1,team2,score1,score2);
ident++;
}
free(conj_jogos);
return 0;
}

问题是 valgrind 说我在"a"函数上有一个堆溢出,我不知道为什么,所以如果有人能提供帮助,我将不胜感激。

程序:

#include<stdlib.h> 
#include<stdio.h>
#include <string.h>
#define MAX_CHARS 1024 /* Max chars for a word*/
#define MAX_SIZE 5 /*Max size for an array*/
jogo *conj_jogos; /*array that saves the jogos*/
static int size_until2 = 0; /*count the size of conj_jogos*/
void a(char nome_jg[],char team1[],char team2[],int score1,int score2)
{
if (jogo_in(nome_jg) == 1) //confirms if the string nome_jg is in conj_jogos
{
printf("%d Jogo existente.n",line);
line++;
}
else if ((nome_in_sis(team1) == 0) || (nome_in_sis(team2) == 0)) //confirms if the strings team1 or team2 are in sistem_eq 
{
printf("%d Equipa inexistente.n",line);
line++;
}
else
{
if (size_until2 < MAX_SIZE)
{
conj_jogos[size_until2] = cria_jogo(nome_jg,team1,team2,score1,score2);
size_until2++;
line++;
}
else
{
jogo *temp;
size_until2++;
temp = realloc(conj_jogos,sizeof(jogo)*(size_until2+1));
free(conj_jogos);
conj_jogos = temp;
conj_jogos[size_until2] = cria_jogo(nome_jg,team1,team2,score1,score2);
size_until2++;
line++;
free(temp);
}
}
}

我无法重新运行代码,因为您的代码中不包含很多相关函数。但我会尝试:

conj_jogos = realloc(conj_jogos,sizeof(jogo)*(size_until2+1));

而不是:

temp = realloc(conj_jogos,sizeof(jogo)*(size_until2+1));

您也可以尝试:

*(conj_jogos + (size_until2 * sizeof(jogo))) = cria_jogo(nome_jg,team1,team2,score1,score2);
size_until2++;

而不是:

conj_jogos[size_until2] = cria_jogo(nome_jg,team1,team2,score1,score2);
size_until2++;

最新更新