Why is this program broken by entering a few elements?

3

Algorithm

At the beginning the array is of length = 0. Then, in each iteration, when trying to enter an element, the array becomes of length + 1; then, said element occupies the position length-1.

Goal

That an element is entered into the array and it changes its length as each iteration occurs.

Problem

The program closes (APPCRASH) by entering a few values.

Implementation

#include <cstdlib>
#include <malloc.h>
#include <iostream>
using namespace std;

int main(int argc, char** argv) {

    int *arreglo, i;
    bool seguir=true;
    size_t longitud=0;
    arreglo=(int*)malloc(longitud*sizeof(int));

    while (seguir!=false) {
        arreglo=(int*)realloc(arreglo,(1)*sizeof(int));
        longitud++;
        arreglo[longitud-1]=5;
        cout<<"seguir: ";
        cin>>seguir;
    }

    for (i=0;i<longitud;i++) cout<<"arreglo["<<i<<"]="<<arreglo[i]<<endl;
    free(arreglo); 
    system("pause");
    return 0;

}

I do not realize what conceptual mistakes I'm making. I have tried several possibilities and the problems persist.

Try to simplify as much as possible the program (to such an extent that the only element that is entered is 5). The original idea was to implement a class to represent the set of integers by a dynamic array, and in that class to define operations on those sets. But the fact is that it is difficult for me to build the sets, and that does not let me move forward in the rest of the year.

I hope you can help me. It's the first time I ask for help with a code. Thank you very much.

    
asked by emi 29.03.2016 в 04:11
source

1 answer

2

The main problem is in this line:

arreglo=(int*)realloc(arreglo,(1)*sizeof(int));
longitud++;

You are not increasing the size of the array. Instead, you are getting a new memory address for an array of length 1. This is because of using this code: (1)*sizeof(int) . Instead of 1 should be the desired length of the array. Change that line of code to the following:

arreglo=(int*)realloc(arreglo,(longitud + 1)*sizeof(int));
                            // aquí está la diferencia
longitud++;

Or reducing it to a single line:

arreglo=(int*)realloc(arreglo,(++longitud)*sizeof(int));

Likewise, realloc will usually return a memory address different from the previous one. If you want to increase the size of your fix at runtime, I recommend you do the following (corrected thanks to @eferion's comment):

  • Store the value of realloc in a temporary variable. Let's say int* nuevoArreglo .
  • If the value of nuevoArreglo is different from NULL , it means that memory relocation could be done, therefore you can reassign the value of the pointer nuevoArreglo to arreglo .
  • The code would be like this:

    //1.
    int *nuevoArreglo = (int*)realloc(arreglo,(longitud)*sizeof(int));
    if (nuevoArreglo != NULL) {
        //2.
        arreglo = nuevoArreglo;
    }
    
        
    answered by 29.03.2016 / 04:19
    source