Jump to content

"Desalocacao" de memoria de Estrutura


Leudassdf
 Share

Recommended Posts

Boas Pessoal,

Eu comecei agora a estudar listas ligadas e estive a tentar fazer um exercício. No final o meu objectivo é libertar a memória.

Eu tentei fazer isso no entanto pelo que consigo constatar através do gestor de tarefas a mesma não está a ser libertada. Ando as voltas e voltas e não descubro o problema.

Será que me sabem identificar o problema?

A estruturas sao as seguintes:

typedef struct veiculo
{
char *marca, *matricula;
int pesoBruto, id_veiculo;
}VEICULO;
typedef struct noveiculo
{
VEICULO *Info;
noveiculo *proximo;
}NOVEICULO;
typedef struct listaveiculo
{
NOVEICULO *Inicio, *Fim;
int nElementos;
}LISTAVEICULO;

typedef struct armazem
{
LISTAVEICULO *LVeiculo;
}GESTAO;

O codigo é o seguinte:

#define _CRT_SECURE_NO_WARNINGS
#define STRING char *
#define MAX_LINHA_FICHEIRO 100
#include <stdlib.h>
#include <stdio.h>
#include "Estruturas.h"
#include <string.h>

GESTAO *CriarEstrutura()
{
LISTAVEICULO *LV = (LISTAVEICULO *)malloc(sizeof(LISTAVEICULO));
if (!LV)
 return NULL;
GESTAO *G = (GESTAO *)malloc(sizeof(GESTAO));

LV->Inicio = NULL;
LV->Fim = NULL;
LV->nElementos = 0;

if (G)
{
 G->LVeiculo = LV;
}
return G;
}
LISTAVEICULO* CarregaVeiculoFim(LISTAVEICULO *LV)
{
if (!LV)
 return NULL;
VEICULO *V;
NOVEICULO * NV;

for (int i = 0; i < 300000; i++)
{
 char *marca = (char *)malloc(50), *mat = (char *)malloc(9);
 strcpy(marca,"MAN");
 strcpy(mat, "AA-AA-AA");
 V = (VEICULO *)malloc(sizeof(VEICULO));
 NV = (NOVEICULO *)malloc(sizeof(NOVEICULO));
 if (!V)
  return NULL;
 if (!NV)
  return NULL;
 if (!LV->Inicio)
 {
  V->id_veiculo = i;
  V->pesoBruto = (i+1) * 100;
  V->marca = marca;
  V->matricula = mat;
  NV->Info = V;
  NV->proximo = NULL;
  LV->Inicio = NV;
  LV->Fim=NV;

 }
 else
 {
  V->id_veiculo = i;
  V->pesoBruto = (i + 1) * 100;
  V->marca = marca;
  V->matricula = mat;
  NV->Info = V;
  NV->proximo = NULL;
  LV->Fim->proximo = NV;
  LV->Fim = NV;
 }
}
return LV;

}
GESTAO *ARMAZEM = CriarEstrutura();
void DestroiDadosVeiculo(LISTAVEICULO *LV)
{
NOVEICULO *aux,*V=LV->Inicio;
int i=0;
while (V)
{
 free(V->Info->marca);
 free(V->Info->matricula);
 aux = V;
 V = aux->proximo;
 free(aux);
 i++;
}
free(ARMAZEM);
}
int main()
{
CarregaVeiculoFim(ARMAZEM->LVeiculo);
DestroiDadosVeiculo(ARMAZEM->LVeiculo);
return 0;
}

Agradeço qualquer ajuda que me possam facultar.

Cumprimentos,

Leandro

Link to comment
Share on other sites

vou somente comentar sobre o problema referdo no tópico : memória não libertada

void DestroiDadosVeiculo(LISTAVEICULO *LV)
{
 NOVEICULO *aux,*V=LV->Inicio;
 int i=0;
 while (V)
 {
   free(V->Info->marca);     // libertar VEICULO.marca
   free(V->Info->matricula); // libertar VEICULO.matricula
   aux = V;
   V = aux->proximo;
   free(aux);                // libertar NOVEICULO
   i++;
 }
 free(ARMAZEM);              // libertar GESTAO
}

o elemento NOVEICULO.Info não tem o direito de ser libertado, visto que foi alocado anteriormente ?

LISTAVEICULO* CarregaVeiculoFim(LISTAVEICULO *LV)
{
// ...
 for (int i = 0; i < 300000; i++)
 {
// ...
   V = (VEICULO *)malloc(sizeof(VEICULO));
// ...
   NV->Info = V;
// ...
}

ps : tira os casts explícitos dos mallocs ...

IRC : sim, é algo que ainda existe >> #p@p
Link to comment
Share on other sites

Antes de mais muito obrigado,

Seguem algumas questões que talvez me possas esclarecer.

vou somente comentar sobre o problema referdo no tópico : memória não libertada

o elemento NOVEICULO.Info não tem o direito de ser libertado, visto que foi alocado anteriormente ?

Já percebi. Obrigado. Efectivamente faz sentido.

Só me faz confusão o seguinte, sendo que o problema anterior ja foi resolvido.

Inicialmente o programa arranca a ocupar 0.3MB na memória. Posteriormente depois de destruir a estrutura acontece que a memoria que ocupa em ram é superior a 0.3, p.ex 0.4,0.8. Quantos mais ciclos forem executados maior é esse valor. Esta situação é normal mesmo depois de fazer o free?

ps : tira os casts explícitos dos mallocs ...porque? nas aulas foi-me dito que teria de ser assim....

Link to comment
Share on other sites

Se fores ver a declaração do malloc ves que ele returna um *void. Antigamente, esse ponteiro era *char, por isso o cast. O teu professor ficou parado no tempo.

Foi exatamente por isso que ele disse que tinhamos de fazer o cast.

Mas se eu testar sem isso fazer o cast dá-me erro. diz que nao é possivel "atribuir" o tipo void * ao tipo int * p.ex. Visual Studio.....

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.