473,394 Members | 1,726 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

stl vector: what is wrong with this code?

The following code causes crash, can someone tell me what the problem is?

#include <iostream>
#include <fstream>

#include <vector>

#include "TClass.h"

using namespace std;

int main(int argc,char **argv)
{
TClass::npts = 2;

vector<TClass> vec;

vec.resize(10);
int len=vec.size();

for(int i=0;i<len;i++)
{
for(int j=0;j<TClass::npts;j++)
{
vec[i].a[j]=j;
vec[i].b[j]=j+1;
cerr <<i<<" "<< vec[i].a[j]<< " " <<vec[i].b[j]<< endl;
}
}

return 0;
}

// TClass.h

class TClass
{
public:

static int npts;
int *a;
int *b;

public:

TClass();
~TClass();

};

// TClass.cpp

#include "TClass.h"

int TClass::npts;

TClass::TClass()
{
a=new int[npts];
b=new int[npts];
}

TClass::~TClass()
{
if(a) delete [] a;
if(b) delete [] b;
}
Jul 19 '05 #1
5 3200
luigi,

try dereferencing TClass::a and TClass::b in the vectors when you set the
member variables

int* a;
a = some memory location
*a = (dereferencing) i.e. the contents of that memory location

vec[i].a[j]=j or in basic form vec[i].a[j]= 0 (first time through) is saying
that a = 0 and when you try and delete memory you dont own...KABOOM
it would be better to say *(vec[i].a[j]) = 0 or j giving you modification of
the contents of the memory location

Hope this helps....

Kevin
"luigi" <lc****@yahoo.com> wrote in message
news:27**************************@posting.google.c om...
The following code causes crash, can someone tell me what the problem is?

#include <iostream>
#include <fstream>

#include <vector>

#include "TClass.h"

using namespace std;

int main(int argc,char **argv)
{
TClass::npts = 2;

vector<TClass> vec;

vec.resize(10);
int len=vec.size();

for(int i=0;i<len;i++)
{
for(int j=0;j<TClass::npts;j++)
{
vec[i].a[j]=j;
vec[i].b[j]=j+1;
cerr <<i<<" "<< vec[i].a[j]<< " " <<vec[i].b[j]<< endl;
}
}

return 0;
}

// TClass.h

class TClass
{
public:

static int npts;
int *a;
int *b;

public:

TClass();
~TClass();

};

// TClass.cpp

#include "TClass.h"

int TClass::npts;

TClass::TClass()
{
a=new int[npts];
b=new int[npts];
}

TClass::~TClass()
{
if(a) delete [] a;
if(b) delete [] b;
}

Jul 19 '05 #2
luigi wrote:
The following code causes crash, can someone tell me what the problem
is? [SNIP] #include "TClass.h"

int TClass::npts;

TClass::TClass()
{
a=new int[npts];
b=new int[npts];
}

TClass::~TClass()
{
if(a) delete [] a;
if(b) delete [] b;
}


You will need to define a copy constructor and an assignment operator for
TClass. Look up The Rule of Three.

WARNING! Untested example code!
WARNING! Code is not exception safe!

// TClass.h

class TClass {
private:
// Make these private

static int npts;

// You will need to know the
// size used here to be able
// to copy
int myNpts;
int *a;
int *b;

public:

void setNpts( int newNpts) {
npts = newNpts;
}
TClass();
TClass(TClass const &);
TClass const &operator=(TClass const &);
~TClass();

};
// TClass.cpp

#include "TClass.h"

int TClass::npts;

TClass::TClass() {
myNpts = npts;
a=new int[npts];
b=new int[npts];
}

TClass::TClass( TClass const &o) {
myNpts = npts;
a=new int[o.myNpts];
b=new int[o.myNpts];
// Copy them using a loop
// or memcpy or std::copy
}

TClass const &
TClass::operator =( TClass const &o) {
// Don't try to copy self
if (this == &o) return;

if (myNpts != o.myNpts) {
delete delete [] a;
delete delete [] b;
a=new int[o.myNpts];
b=new int[o.myNpts];
}
// Copy them using a loop
// or memcpy or std::copy
}

TClass::~TClass() {
// if(a) delete [] a;
// No need for the if,
// you can delete a 0
// pointer
delete [] a;
delete [] b;
}

// Do not forget to define npts
int TClass::npts = 2;
// 2 is just an arbitrary default
--
Attila aka WW
Jul 19 '05 #3

<kf*****@kc.rr.com> wrote in message
news:s%******************@twister.rdc-kc.rr.com...
luigi,

try dereferencing TClass::a and TClass::b in the vectors when you set the
member variables

int* a;
a = some memory location
*a = (dereferencing) i.e. the contents of that memory location

vec[i].a[j]=j or in basic form vec[i].a[j]= 0 (first time through) is saying that a = 0 and when you try and delete memory you dont own...KABOOM
it would be better to say *(vec[i].a[j]) = 0 or j giving you modification of the contents of the memory location

Hope this helps....

Kevin


Kevin,
[Please post your answers after the text you're referring to (or
interspersed with it at least).]

Your answer is not correct. The OP allocated two arrays of int, not two
arrays of pointers. Your method will try to dereference the int at
vec[i].a[j], but that's not allowed, since they're not pointers. The line
"a = new int[npts]" allocates an array of ints of size npts, and the
notation a[j] refers to the int at index j in that array. Also, setting
vec.[i].a[j] = 0 will set a[j] to 0, not a. The pointer 'a 'points to
memory somewhere else, where the int's are actually stored. The int's are
*not* stored at the address of 'a', but at the address 'a' *points to*.

The OP's problem has to do with a lack of a proper copy-constructor, I
believe. (See Attila's response.)

-Howard



Jul 19 '05 #4
Thanks! The problem is fixed with the copy constructor. I will take
the rules more seriously from now on :->).

The resize(10) command calls default constructor once, then the copy
constructor 10 times, then destructor once. Very strange.
Jul 19 '05 #5

"luigi" <lc****@yahoo.com> wrote in message news:27**************************@posting.google.c om...
Thanks! The problem is fixed with the copy constructor. I will take
the rules more seriously from now on :->).

The resize(10) command calls default constructor once, then the copy
constructor 10 times, then destructor once. Very strange.


Not strange at all. The declaration of resize is:

resize(size_type sz, T c = T());

The second argument is an element that is used to initialize (by copy
construction in your observations) the newly created elements in the
array. Vector does not require that the contained type be default
constructable. In that case, you must provide a prototype object
for it to copy over these elements.

class C {
public:
int C(int); // no default constructor
};

vector<C> v;
v.resize(10, C(1));

Jul 19 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: Hitesh Bhatiya | last post by:
Hi all, I have written a small program to accept some socket connections, which are then added to a vector (using push_back). But after a few calls to the push_back function, it deleted the...
2
by: Sims | last post by:
Hi, I have a structure as follow struct sIntStructure { int m_nNumber; // // A few more variables //
7
by: Jerry Krinock | last post by:
I've declared a class that has some std::vector data members like this: class MyClass { public: ... std::vector<Apples> apples ; ... private: ...
7
by: hellwolf | last post by:
Hi,everyone.Because of my English level,I will try to use code to explain where I confused. //list of code: #include <iostream> #include <algorithm> #include <vector> class A{ static int...
8
by: Hagen | last post by:
Hi, I have a question that you probably shouldn´t worry about since the compiler cares for it, but anyways: When you run your compiler with optimization turned on (eg. g++ with -Ox flag) and...
33
by: Simon | last post by:
Hi, I am going to use quite a few vectors and I want to make sure I am using it properly. // struct MYSTRUCT { .... }
6
by: Rahul K | last post by:
Hi I am working on Visual Studio on Windows. I have a function which return the list of all the IP Addresses of a machine: vector<char *getAllLocalIPAddress() { char localHostName; struct...
18
by: imutate | last post by:
I have an integer variable and I am testing it as follows #define NULL_VAL -1 ... if (x.id != NULL_VAL) { std::cout << x.id << std::endl; ... }
11
by: mathieu | last post by:
Hello, I would like to implement a 'vector<uint12_t>' structure, where uint12_t is a 12bits unsigned integer. AFAIK I need to completely duplicate the implementation of let say vector<booland...
4
by: Josefo | last post by:
Hello, is someone so kind to tell me why I am getting the following errors ? vector_static_function.c:20: error: expected constructor, destructor, or type conversion before '.' token...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.