Question

These are the structs I defined (don't mind the language):

typedef struct cliente
{
    char* primeiroNome;
    char* ultimoNome;
}Cliente;

typedef struct data
{
    int dia;
    int mes;
    int ano;
}Data;

typedef struct reserva
{
    Data* data;
    int numReservas;
    struct cliente* cliente;
    struct reserva* next;
}Reserva;

Then I created a list:

Reserva* novaListaReservas() // in English the name would be something like newReservationsList()... I guess
{
    Reserva* lista = (Reserva*)malloc(sizeof(Reserva));
    lista->next = NULL;
    lista->numReservas = 0;
    return lista;
}

Then in some function I did this (well not quite but for e.g. assume it was):

Reserva* reserva = novaListaReservas();
Cliente* cliente = (Cliente*)malloc(sizeof(Cliente));
Data* data = (Data*)malloc(sizeof(Data));

data->dia = 30;
data->mes = 4;
data->ano = 2014;

cliente->primeiroNome = (char*)malloc(15 * sizeof(char));
cliente->ultimoNome = (char*)malloc(15 * sizeof(char));

reserva->data = data;
reserva->cliente = cliente;

/*stuff done here/*
//End of Function

Now I'm in some other function that only has (Reserva* reserva) as a parameter I tried:

free(reserva->cliente->primeiroNome);
free(reserva->cliente->ultimoNome);
free(reserva->cliente);
free(reserva->data);

But I don't think it's working because after this I still can access reserva->data->dia/mes/ano...

What's wrong with the way I'm freeing? Is there a way to check if the free 'worked'?

Était-ce utile?

La solution

You can still access freed memory, but it's undefined behavior. It might still contain the "old" data, or it might now contain something completely bogus.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top