Dynamic allocation of vectors

Asked

Viewed 522 times

4

Follows the statement:

Make a program that reads keyboard numbers and store them on one dynamically allocated array. The user will type in a sequence of numbers, no quantity limit. The numbers will be typed one by one and, if he wishes to close the data entry, he will enter the ZERO number. The data must be stored in the memory of this way

  • Start with a dynamically allocated size 10 vector;
  • Apos, if the allocated vector is full, allocate a new vector of the previous vector size by adding space for another 10 values (size N+10, where N starts with 10);
  • Copy the values already typed from the initial area to this larger area and free the initial area memory;
  • Repeat this procedure to expand dynamically with another 10 values the allocated vector each time it is full. So the vector will be 'expanded' by 10 values.

At final, display the read vector. Do not use the REALLOC function.

I’m pretty new yet, so there’s probably a lot of things wrong with my code.

I tried to use a second vector, pass everything to it, allocate 10 more spaces in the main vector and then pass it all on to it again.

However, when I type I get to 19 and the program stops. In the first 10, it works perfectly, but then when I allocate another 10 (in case the vector would have 20 spaces) it doesn’t work.

Follow the code I made:

#include <stdio.h>
#include <stdlib.h>

int main(){
    int *vet, c=1, c2=0, *vet1, aux;

    vet =(int*) calloc(10, sizeof(int));

    do {
        scanf("%d", &aux);

        if (c == 10){

            vet1 = (int*) malloc (c2 * sizeof(int));

            for (int i=0; i<c2+1; i++) vet1[i] = vet[i];    

            vet = (int*) malloc (c2 * sizeof(int));

            for (int i=0; i<c2; i++) vet[i] = vet1[i];

            c = 1;
        }

        c++;
        c2++;
        vet[c2] = aux;

    } while (aux != 0);

    printf("\n\n")    ;
    for (int i=0; i<c2; i++) printf("%d  ", vet[i]);

    system("pause");
    return 0;
}
  • And why not use realloc()? Anything else you can’t use? I can see several problems in the code.

  • because it is in the statement.. only that very says not to use

  • 1

    What is this: for (int i=0; i<c2; i++) vet[i] = vet[i];? Ps: It is better to write the statement. It is not possible to understand very well by your code

  • ah, this part I had fixed but could not save (power outage). now I tidied up there. is vet[i] = vet1[i] to pass everything that is in vet1 to the vet

2 answers

4


One of the reasons for the confusion is that code uses variable names that are difficult to understand what they mean. With better names one can follow better what is happening. The code does more than it should and falls into some traps.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {
    int indice = 0, indiceParcial = 0;
    int *vetor = malloc(sizeof(int) * 10);
    while (1) {
        int valor;
        scanf("%d", &valor);
        if (valor == 0) break;
        vetor[indice++] = valor;
        if (indiceParcial++ == 9) {
            int *vetorAuxiliar = malloc(sizeof(int) * (indice + 10));
            memcpy(vetorAuxiliar, vetor, indice * sizeof(int));
            free(vetor);
            vetor = vetorAuxiliar;
            indiceParcial = 0;
        }
    }
    printf("\n");
    for (int i = 0; i < indice; i++) printf("%d  ", vetor[i]);
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • Only declare the variable when you need it
  • You don’t need the calloc() and should not do cast of the result.
  • I’m not worried about the test to see if the allocation spoke because in exercise like this will not fail
  • This is a typical endless loop since the output is in his brain has no reason to use condition
  • Once the value is entered you must determine whether to continue or exit the loop
  • The first thing that must operate is the addition of the value in the vector
  • Then analyze whether the vector has filled and should perform a relocation and copy
  • When to recreate you create based on the current size plus 10, as stated
  • And use memcpy() which is ready and reliable function to copy data. It uses the sizeof in it for the same reason as in malloc(), these functions operate on the basis of char, then byte copy per byte, and if you have a number of elements of a multibyte type you need to multiply by that number
  • You can’t forget to release the memory of the previous vector
  • And then we adopt the new vector created as the standard by copying its address (vetor becomes null after the free(), if all goes well)
  • And we reset the partial index you control when you break the limit. It is possible to delete this variable and make a indice % 10, but it is almost certain that it will be slower since the division is with large margin the slower operation of the processor. Or use one thing or another, you need to decide if you want simpler code or more performance
  • Maybe you should wear one for reducing scope of 2 variables.
  • What is your implication in the execution of the program when we define the same variable N times? As is the case with the int value within the cycle, the variable value will always be modified at the memory location?

  • When doing vector = vector Auxiliar; it will be losing the memory site of the vector Auxiliar, it will be impossible to give free() keeping memory Leaks, correct? We are increasing more and more the useless memory of the program

  • None, statement is something that only exists in code, not in execution. It’s actually good to be only in the scope that is used. If the two variables point to the same place how is it impossible to free the memory? In fact what your answer does is meaningless. Copy twice and release twice the same thing.

  • If the person who denied can inform the problem I try to fix.

  • It doesn’t make sense because it’s the typical exercise of those who start to learn to manage memory, it’s a test to know whether to allocate and give free correctly. So the rest of the answers make sense, it’s only going to cost in performance by having cycles there. If you run Valgrind you will surely accuse that memory Leak.

  • Teaching to do wrong never makes sense! There are no leaks there, you need to study more about pointers.

  • Yes, I’ll have to study more on pointers, just a free at the end of your code, which does not cause much damage. But I still have to thank you for warning me about possible mistakes in my code

  • 1

    At the end of the code does not even cause, the end of the execution frees the memory, I could even put, and maybe put the alert that in a code that did not end there could put a free() final, but there is no leak for the reason you spoke. The negative was only by the lack of the free() in the end that does not cause any problem? In fact it is only time spent on doing what the operating system will have to do anyway.

  • My teachers always told me to give free at the end, even if it didn’t make sense to me for the reason I said it. Thank you so much for what you do to this community, I always try to be learning in this area .

  • And they’re right, but you have to have context, it’s what goes wrong in the other question, you have to understand what happens and not follow formulas, good practices, you have to understand the context to apply what you need, it’s not wrong, but it’s not necessary in every context. And thank you, I try to maintain the order and quality of everything I can, it’s not easy and it takes work to do what little I can. Change the way you learn and evolve freely, you can do it, I tell a lot of people that I know you don’t have, you just have to find the way.

Show 5 more comments

0

Following your style...

#include <stdio.h>
#include <stdlib.h>

int main(){
    int *vet, c=0, c2=0, *vet1, aux, N=1;

    vet =(int*) calloc(10, sizeof(int));

    do {

        scanf("%d", &aux);
        if(!aux) break;

        if (c%10 == 0){
            N++;
            vet1 = (int*) malloc (N*10 * sizeof(int));
            for (int i=0; i<(10*(N-1)); i++) vet1[i] = vet[i];    
            free(vet);
            vet = (int*) malloc (N*10 * sizeof(int));
            for (int i=0; i<(10*(N-1)); i++) vet[i] = vet1[i];
            free(vet1);
        }
        c2++;
        vet[c++] = aux;
    } while (aux);

    printf("\n\n");
    for (int i=0; i<c2; i++) printf("%d  ", vet[i]);
    printf("\n");
    free(vet1);
    free(vet);

    return 0;
}
  • You are creating memory Leaks and not adding 10 more capacity, but TIMES 10

  • You didn’t understand the code so... it grows from 10 to 10 yes.. Times 10, but N = N+1 whenever c is multiplied by 10. First it’s 20, then 30, 40... and so on.

  • Yes, you’re right, but the serious problem is even in memory management, is committing many memory Leaks, is giving mallocs without giving free

  • Just missed the free, I’ll edit ^^

  • ==15332== All heap Blocks Were Freed -- no Leaks are possible

  • There is another problem, if you type 10 numbers the program to, due to its use of the variable c

Show 1 more comment

Browser other questions tagged

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