dimanche 21 octobre 2018

Initializing vector of objects fail due to pointer being freed was not allocated ERROR

Below is the sample class that i have created and all need to create a vector of objects of below class

#include <stdio.h>
#include "myvector.h"
#include <iostream>

class myvector
{
private:
  double *elem;
  int sz;

public:
  myvector()
  {
    std::cout << " In Constructor \n";
  }

 ~myvector()
 {
   std::cout << " In Destructor \n";
   delete[] elem;
 }

 myvector(int s)
 {
   std::cout << " In Param Cons \n";
   elem= new double[s];
 }
 myvector::myvector(const myvector& that)
 {
    this->sz=that.sz;
    this->elem=that.elem;
 }

myvector&  operator=(const myvector& that)
{
  return *this;
}
};

Below is the main function

#include <iostream>
#include "myvector.h"
#include <vector>

int main(int argc, const char * argv[]) {
// insert code here...
 myvector abc(10);
 std::vector<myvector> abc(10,10);
 getchar();
 return 0;
}

myvector abc[10];  works perfectly and creates an array of objects

But as i need to call the parameter constructor for all these objects i have used below

std::vector abc(10,10);

This actually is not creating an array and is failing with the error

vector(16828,0x10013e380) malloc: * error for object 0x100400050: pointer being freed was not allocated * set a breakpoint in malloc_error_break to debug

And parametric function was not even called 10 times , its called just once

Aucun commentaire:

Enregistrer un commentaire