Good I was trying to practice with vectors with dynamic memory and I got this error when executing:
Violación de segmento ('core' generado)
The fact is that sometimes it works, so it leaves me a little confused, this is my code:
#include <iostream>
#include <fstream> // ifstream
using namespace std;
struct VecDin {
int *datos;
int n;
};
// FIXME 1: Redimensions v para que se quede con "nuevo" elementos
void ReSize(VecDin& v,int nuevo)
{
if(nuevo >= 0) {
if(nuevo != v.n) {
if(nuevo != 0) {
int *datos_nuevos;
datos_nuevos = new int[nuevo];
if(v.n > 0) {
int minimo = v.n < nuevo ? v.n : nuevo;
for(int i = 0; i < minimo; i++)
datos_nuevos[i] = v.datos[i];
delete[] v.datos;
}
v.datos = datos_nuevos;
v.n = nuevo;
}
else {
delete[] v.datos;
v.datos = 0;
v.n = 0;
}
}
}
}
// FIXME 2: Lee objetos int hasta final de flujo y devuelve VecDin con los datos (usa ReSize)
VecDin LeerVecDin(istream& flujo)
{
VecDin v;
int n = 1;
while(flujo.good()) {
ReSize(v,n);
flujo >> v.datos[n-1];
++n;
}
return v;
}
// FIXME 3: Muestra en un flujo de salida los datos enteros de un VecDin (ver main)
void Mostrar(VecDin vector, ostream& os)
{
for(int i = 0; i < vector.n || !os.good(); i++)
os << vector.datos[i] << " ";
}
// FIXME 3: Libera la memoria reservada en un VecDin (ver main)
void Liberar(VecDin v)
{
delete[] v.datos;
v.n = 0;
}
int main(int argc, char *argv[])
{
VecDin v= {0,0};
if (argc==1)
v= LeerVecDin(cin);
else {
ifstream f(argv[1]);
if (!f) {
cerr << "Error: Fichero " << argv[1] << " no válido." << endl;
return 1;
}
v= LeerVecDin(f);
}
Mostrar(v,cout);
Liberar(v); // Libera la memoria reservada
}
If you could give me a clue as to why, as I suppose it is what happens, access outside the memory that corresponds to it would help me a lot.
Thank you!