[英]reading from a matrix, allocated with malloc, AddressSanitizer: heap-buffer-overflow
[英]Heap buffer overflow in allocated array
所以我有这个程序,它有一个结构和一个数组。 该数组是conj_jogos
,它是一个名为 jogo 的结构的数组,其 MAX_SIZE(MAX_SIZE 为 5)。
结构:
typedef struct
{
int id;
char equipas[2][1024];
int pont[2];
char nome[MAX_CHARS];
} jogo;
所以要创建这个数组,我在我的主 function 中分配了 memory,如下所示:
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”function 上有一个堆溢出,我不知道为什么,所以如果有人可以提供帮助,我将不胜感激。
程序:
#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++;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.