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

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

所以我有一个具有结构和数组的程序。数组是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);
        }
    }
}
c arrays dynamic-memory-allocation heap-corruption
1个回答
0
投票

我无法重新运行代码,因为您的代码中没有包含太多相关功能。但我会尝试:

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++;
© www.soinside.com 2019 - 2024. All rights reserved.