Problems with dynamic allocation

Asked

Viewed 332 times

5

In an exercise I need to make a record of a struct possibly declared as follows:.

typedef struct Locatarios {
    char nomeLocatario[MAX_NOME];
    int codigoLoc;
    float valorAluguel;
} Locatarios;

It is necessary to use dynamic allocation to register one tenant at a time, so do not ask before how many will be registered. I did so:

Locatarios *pLocatarios;
pLocatarios = malloc(sizeof(Locatarios));

As far as I understand, the allocation worked perfectly and the registration is working. What I can’t figure out how to do is that codigoLoc cannot be repeated while registering.

How I traverse a structure that has been dynamically allocated in search of a value?

Below is the function that performs the research;

int verificaCodigo (int *codigo, int *contador) {
// Declarações locas
    Locatarios *pLocatarios;
    int aux = 0, totalLocatarios = 0;
// Instruções
    totalLocatarios = (sizeof(pLocatarios) / sizeof(pLocatarios[0]));
    pLocatarios = malloc(sizeof(Locatarios));
    if (pLocatarios != NULL) {
        for (aux = 0; aux < contador; aux++) {
            if (pLocatarios[aux].codigoLoc == codigo) {
                return 1;
            }
            break;
        }
        free(pLocatarios);
        pLocatarios = NULL;
    }
    else {
        printf("ERRO NA ALOCAÇÃO DE MEMÓRIA!");
    }
    return 0;
 }
  • Show what you have already done. I already tell you that you will have to keep all tenants in some organized way. will need a way that you know where they are all, probably in a array. That one array probably will have to grow dynamically through a structure of its own that allocates the parts gradually (as a linked list) or will have to copy the data to a new one array each time you add an element. Or you can optimize this and create with an established minimum size and only grow it at specific times.

  • I suppose a 'linked list' extrapolates the content I can use to solve this exercise. In my first test of the program, I thought after finishing the registration of a renter, write your data in a file, which would facilitate the search for this code. The result of a registration was this => Jose ? 0x01 OS=Windows_nt Path= @ÃDŽ.

  • There is no problem to write the contents in file but to do this only to have access to the list of tenants does not make sense and deep down you would still need a solution to form this list.

  • I will reply but I could not give such a complete answer because I have not seen other, perhaps relevant parts of the code. It doesn’t matter so much, I just can’t be more specific. You’ll have to manage with the information I’ll post.

  • I don’t think there are relevant parts of the code. There is only the function cadastraLocatario() requesting the three data, using dynamic allocation. But with what you commented I think I have enough material to research further and try to solve the problem.

  • It might help to see if there are other mistakes, because there are several there in what you posted. I am responding, just give me a time I have some other things that have not let me conclude now, but put later.

  • Is it C or C++ ? If it is C++ you can use Vector<Locatarios>

  • @Tony Should be done in C.

Show 3 more comments

1 answer

5


Apparently his verificaCodigo() is in general on the right track. There are some problems in your code as a whole that I have seen passing the eye:

  • I do not understand why the two parameters need to be passed as pointers, I believe it is by mistake, if it is not have more errors because this way you are accessing the memory address and not the data you want (hence may be picking dirt).
  • I don’t know what the break is doing there, it certainly cannot exist. A break out of a if is not usually useful for anything.
  • Why is there a memory allocation in a function that only checks something? Either it checks something or it creates the new element (if that was the intention). Making the allocation in one place and letting the fill in in another aggravates the disorganization.
  • If there is an allocation error in memory the return is 0 which is the same return if it does not find an equal code (duplication), this makes no sense.
  • Apparently you know how many tenants are registered, this is what you get in contador. If this is it, why calculate the totalLocatarios that isn’t even being used?
  • Apparently there are other errors in using pointers for past information, since you are picking up dirt in memory.
  • There are some problems where your code would not be reliable but I think it is not relevant to who is learning.
  • It is not a problem but I do not like the names of the variables you use, they do not indicate well what you are serving, just indicate one thing and do another. You call your kind of structure Locatarios but there only fits one tenant. The pointer to the array makes sense in the plural.
  • Since it’s just an exercise I won’t even mention problem of keeping a monetary value in float.

Probably the simplest solution for what you want is to do relocations of pLocatarios every time you add a new element. It may not be very efficient but it solves it. And so your duplicity check function will make sense. It would be something like that:

pLocatarios = realloc(pLocatarios, (sizeof(pLocatarios) / sizeof(pLocatarios[0]) + 1) * sizeof(pLocatarios[0]);

This is taking the amount of elements in array, adding 1 and allocating this amount times the size of each element. You will need to do this anates operation to add a new tenant.

If you keep the number of renters stored somewhere it gets a little easier, maybe:

pLocatarios = realloc(pLocatarios, (totalLocatarios + 1) * sizeof(Locatarios);

This allocation should be done where you will add data of the new tenant. In practice it is possible to create a code only with the realloc() since if the initial pointer is NULL he acts exactly like malloc.

Maybe it won’t even be too inefficient since the operating system can, in some cases, make optimizations in the allocation that avoids data copying. Anyway for an exercise it doesn’t matter.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.