Issue in allocating memory for resizing stack - c++

I have tried and tried to figure the mistake in my code , but I still can't find it.I have a Stack class Album, which i want to resize, and think i did it right.For some reason however most of the times the program crashes and maybe one in 10 works fine and I have no idea why.If you could point the mistake that would be great. So here is the code:
const Song Song::null_song;//static from Song class
class Album
{
Song* songs;
char* name;
int top;
int capacity;
bool full () const;
void resize ();
public:
...
}
And here are the functions, somewhere in them is the culprit.The problem happens when I try to push more items in Album then the predefined INIT_CAPACITY=4.I think it should work, but it doesn't, so the problem must be allocating the new memory.
const int INIT_CAPACITY=4;
std::ostream& operator<<(std::ostream& os, Album& p)
{
os<<"Name of Album:"<<p.name<<std::endl;
for(int i=0;i<=p.top;i++)
os<<p.songs[i]<<std::endl;
}
Album::Album(const char* p)
{
int len1=strlen(p);
name=new char [len1+1];
strcpy(name,p);
top=-1;
songs = new Song[INIT_CAPACITY];
capacity = INIT_CAPACITY;
}
Song Album::pop()
{
if (empty())
return Song::null_song;
return songs[top--];
}
Song Album::last() const
{
if (empty())
return Song::null_song;
return songs[top];
}
bool Album::push(Song x)
{
if (full())
resize();
songs[++top] = x;
return true;
}
void Album::resize()
{
capacity *= 2;
Song* newsongs = new Song[capacity];
for(int i = 0; i < capacity / 2; i++)
newsongs[i] = songs[i];
delete[] songs;
songs = newsongs;
}
bool Album::empty() const
{
return top == -1;
}
bool Album::full() const
{
return top == capacity-1;
}
Album::Album()
{
top=-1;
songs = new Song[INIT_CAPACITY];
capacity = INIT_CAPACITY;
name=new char [1];
name[0]='\0';
}
Album::~Album()
{
delete [] songs;
delete [] name;
}

Your Song also uses char* where it should use std::string.
It deletes this pointer in the destructor, but you haven't defined an assignment operator or copy constructor.
This makes all Songs contain invalid pointers once you have resized an Album.

Related

the code doesn't display and doesn't run either

Below is a program that has class definitions for Item, Customer and Sales. The main simply creates object object of each class and test its member functions. Modify the main program such that it provides a menu driven interface where user can create objects of Item, Customer and a complete a sales transaction with the sales object.The program should also have an option for display the records of items,customers and sales.To make your program more useful,include file handling such that when objects are created for Items,Customers and Transaction,the user will be prompted to save the recordon the file or not.
here's the code it's not displaying anything pleasee help i'm running it by Dev c++
#include <conio.h>
#include <iostream>
#include <string.h>
using namespace std;
class Item {
int itemCode;
private:
double price;
double discount;
protected:
int qtyOnStock;
char *name;
public:
Item() {
itemCode = 0;
strcpy(name, "UNKNOWN");
price = 0;
discount = 0;
qtyOnStock = 100;
}
void setItemCode(int c) { itemCode = c; }
int getItemCode() { return itemCode; }
double getPrice() { return price; }
void setPrice(double p) { price = p; }
void setDiscount(double d) { discount = d; }
double getDiscount(double d) { return ((d < 20 ? d : 20) / 100 * price); }
void setName(char *n) { name = n; }
char *getName() { return name; }
void setQtyOnStock(int q) { qtyOnStock = q; }
int getQtyOnStock() { return qtyOnStock; }
};
class Customer {
private:
int id;
char *name;
char *contactNo;
int type;
public:
Customer() {
id = 0;
strcpy(contactNo, "No Num");
strcpy(name, "No Name");
type = 0;
}
void setId(int newId) { id = newId; }
int getId() { return id; }
void setName(char *n) { strcpy(name, n); }
char *getName() { return name; }
void setContactNo(char *c) { strcpy(contactNo, c); }
char *getContactNo() { return name; }
};
class Sales {
private:
Item item;
Customer cust;
char *date;
int qtySold;
public:
Sales() { date = "mm-dd-yyyy"; }
void setItem(Item newItem) { item = newItem; }
Item getItem() { return item; }
void setCustomer(Customer newCust) { cust = newCust; }
Customer getCustomer() { return cust; }
void setDate(char *newDate) { strcpy(date, newDate); }
char *getDate() { return date; }
void setQtySold(int newQty) { qtySold = newQty; }
int getQtySold() { return qtySold; }
};
int main() {
Item item1;
Customer cust1;
Sales sales1;
item1.setItemCode(143);
item1.setName("Ballpen");
item1.setPrice(12.5);
item1.setQtyOnStock(250);
cust1.setId(123);
cust1.setName("Juan dela Cruz");
sales1.setItem(item1);
sales1.setCustomer(cust1);
sales1.setDate("10-27-2018");
sales1.setQtySold(98);
item1.setQtyOnStock(item1.getQtyOnStock() - sales1.getQtySold());
system("cls");
cout << sales1.getItem().getName() << endl << item1.getQtyOnStock();
getch();
return 0;
}
The main and biggest proble is that you do C-style string handling with char* and even that in a wrong way.
If you would enable all warning in your compiler, it would already tell you the problems. My VS2019 gives 15 errors, 1 warning and 7 messages, when I try to compile your code. Please see:
So, the main problem is that you are using char* that are not initialzed, meaning they point to somehwere, and that you do not allocate memory to store your strings.
So all your strcpy functions will fail and probably crash your system. Also the assignments to a char* will fail in most cases.
You will overwrite some random memory.
All this can be immediately fixed, without big problems, if you would use std::string instead of char*. Because char* are that error prone, C++ introduced the std::string, so, please use it.
Sometimes you have C++ teachers that want you to use char*. Those teachers should be fired. But if you really need to use char*. Then you must allocate memory, before coping data.
Let us assume that you have a string "myName" and you want to copy that.
char* name{};
name = new char[strlen(myName)+1]; // +1 for the trailing '\0'
strcpy(name, myName);
// ...
// ...
// Do stuff
// ...
// ...
delete [] name; // Release memory at the end
But as said. Simply use std::string
Your program as is, cannot work. You need a major refactoring.
In your Item class:
protected:
int qtyOnStock;
char *name;
public:
Item() {
itemCode = 0;
strcpy(name, "UNKNOWN");
price = 0;
discount = 0;
qtyOnStock = 100;
}
name is an unitialized char pointer so copying to it will result in UB.
change char* name to std::string name, replace strcpy(...) name = "UNKNOWN".
Normally though you initialize member variables like this:
Item()
: itemCode(0), itemCode(0), name("UNKNOWN"), price(0), discount(0), qtyOnStrock(100)
{}
a newer compiler lets you initialize in other ways like when declared e.g.:
protected:
int qtyOnStock{100};
std::string name{"UNKNOWN"};
...

Program fails when I call a method from constant reference

So, I have a token class:
Token.h
class Token {
std::string name; // token name
int frequency;//frequency
Vector lines;//lines where the token is present
public:
//explanations for the methods in the Token.cpp
Token(std::string tokenname, int linenumber);
virtual ~Token();
const Vector getLines() const;
};
#endif /* TOKEN_H_ */
Token cpp
Token::Token(string tokenname, int linenumber) {
// TODO Auto-generated constructor stub
name = tokenname;
frequency=1;
lines.push_back(linenumber);
}
Token::~Token() {
// TODO Auto-generated destructor stub
}
std::string Token::getName() const{
return name;
}
int Token::getFrequency() const{
return frequency;
}
const Vector Token::getLines() const{
const Vector vec = lines;
return lines;
}
The program fails, when I pass it to the insert method of list class
class List {
private:
class Node {
public:
Token data;
Node* next;
Node(const Token &dataItem, Node* nextptr);
~Node();
};
Node* first;
int length;
public:
List();
virtual ~List();
void insert(const Token &t);
};
List.cpp:
List::Node::Node(const Token &dataItem, Node* nextptr): data(dataItem), next(nextptr){
}
List::Node::~Node(){
cout<<"dead"<<endl;
}
List::List() {
// TODO Auto-generated constructor stub
length = 0;
first = nullptr;
}
List::~List() {
// TODO Auto-generated destructor stub
Node* temp = first;
Node* newtmp;
while(temp->next != nullptr){
newtmp = temp->next;
delete temp;
temp = newtmp;
}
}
const int List::size(){
return length;
}
void List::insert (const Token &t){
Vector dammit = t.getLines();
}
I found out which line in the insert does it(Vector dammit = t.getLines()), so I leave it like that.
It gives me this error message:
double free or corruption (fasttop): 0x0000000000c34040 ***
And here something from main file if you want to run:
int main() {
// cout<<"tokens are here"<<endl;
//
Token hit("aca", 1);
Token hit2("ui", 2);
Token hit1("111", 3);
List list;
list.insert(hit);
list.insert(hit2);
list.insert(hit1);
}
Vector class:
class Vector {
int* store;
int capacity;
int next_index;
public:
Vector();
Vector(int initial_size);
Vector(const Vector &v);
virtual ~Vector();
void push_back(int item);
int pop_back();
const int size() const;
void resize();
void operator =(const Vector &v);
int& operator[] (int k);
const int& operator[] (int k) const;
friend std::ostream& operator<<(std::ostream& os, const Vector& v);
};
Vector::Vector() {
// TODO Auto-generated constructor stub
store = new int [1];
capacity = 1;
next_index = 0;
}
Vector::Vector(int initial_size){
store = new int [initial_size];
capacity = initial_size;
next_index = 0;
}
Vector::Vector(const Vector &v){
store = v.store;
capacity = v.capacity;
next_index = v.next_index;
}
Vector::~Vector() {
// TODO Auto-generated destructor stub
delete[] store;
}
void Vector::resize(){
std::cout<<"in resize"<<std::endl;
std::cout<<capacity<<std::endl;
int length = capacity;
capacity+=100;
int* tempArray;
tempArray = new int[capacity];
for (int i=0; i<length; i++){
tempArray[i] = store[i];
}
if (length>1)
delete[] store;
std::cout<<"finish re4size"<<std::endl;
store = tempArray;
}
void Vector::push_back(int item){
if(next_index >= capacity)
this->resize();
store[next_index] =item;
next_index++;
}
int Vector::pop_back(){
next_index = next_index-1;
int last = store[next_index];
return last;
}
void Vector::operator =(const Vector &v){
//delete[] store;
store = v.store;
capacity = v.capacity;
next_index = v.next_index;
}
const int Vector::size() const{
return next_index-1;
}
int& Vector::operator[] (int k){
//assert((k<next_index)&(k>=0));
return store[k];
}
const int& Vector::operator[] (int k) const{
//assert((k<next_index)&(k>=0));
return store[k];
}
ostream& operator<<(ostream& os, const Vector& v)
{
for(int i=0; i<=v.size(); i++){
os << v[i]<< ' ';
}
return os;
}
In
Vector::Vector(const Vector &v){
store = v.store;
capacity = v.capacity;
next_index = v.next_index;
}
You now have two vectors pointing to the same int* store;
In
void Vector::operator =(const Vector &v){
//delete[] store;
store = v.store;
capacity = v.capacity;
next_index = v.next_index;
}
You do the same thing.
when you call
const Vector Token::getLines() const{
const Vector vec = lines;
return lines;
}
vec = lines uses the copy constructor. You now have vec and lines pointing to the same store.
You return a copy of lines, this will trigger the copy constructor again. A third object now points to store.
When the stack unrolls, locally defined vec is destroyed. ~Vector deletes store. You now have two objects pointing to the same de-allocated store.
Kaboom! as soon as you try to do much of anything else with either of those Vectors. Looks like the destruction of the returned Vector hits first and causes the destructor to re-delete store.
You need to allocate storage for a new store and then copy the contents of source store into the new store in the = operator and the copy constructor.
Vector::Vector(const Vector &v){
capacity = v.capacity;
store=new int[capacity];
for (size_t index; index < capacity; index++)
{
store[index] = v.store[index];
}
next_index = v.next_index;
}
and
Vector & Vector::operator =(const Vector &v){
delete[] store;
capacity = v.capacity;
store=new int[capacity];
for (size_t index; index < capacity; index++)
{
store[index] = v.store[index];
}
next_index = v.next_index;
}
std::copy can be used in place of the for loop in C++11. Hoary old memcpy can also be used, but only because store is a primitive data type.
And while I'm editing, thanks Jarod42, one more little tweak:
const Vector & Token::getLines() const{ //note the return of a reference. This avoids
// making a copy of lines unless the caller really
// wants a copy.
// const Vector vec = lines; don't need to do this. lines is const-ified by the
// const on the return type of the function
return lines;
}
This error has nothing to do with calling a method with constant reference, but rather the function getLines(). For example, should you take hit1 and call the function getLines() directly, it will crash nonetheless. The issue is with how Token has a stack-allocated attribute Vector, which in turn has an int * attribute. This isn't necessarily an issue, but depending on how you implement those classes it can cause memory conflicts.
If you want to keep using your getLine() and can't use the <vector> libraries, you could change your Token's lines attribute to a Vector * and change all other syntax accordingly. Also remember to initialize your pointer lines memory or else it will crash.
However, I'd prefer to use as less dynamic-allocated memory as possible, if unnecessary. And like another user said, before while(temp->next != nullptr) you should have a condition if(temp != nullptr )

C++ MovieList array and pointer

I'm still a bit stuck on another part on my assignment.
Here is what the prompt is asking:
Now you can modify the LoadMovies function to create a MovieList
object and add each of the Movie objects to it. The function
LoadMovies should return a pointer to the MovieList object. That means
you need to create the MovieList object dynamically and on the heap.
Change the main function and store the returned MovieList pointer in a
variable. To test if everything works as expected, you can use the
PrintAll function of the MovieList object.
Here is my code so far:
class MovieList {
public:
Movie* movies;
int last_movie_index;
int movies_size;
int movie_count = 0;
MovieList(int size) {
movies_size = size;
movies = new Movie[movies_size];
last_movie_index = -1;
}
~MovieList() {
delete [] movies;
}
int Length() {
return movie_count;
}
bool IsFull() {
return movie_count == movies_size;
}
void Add(Movie const& m)
{
if (IsFull())
{
cout << "Cannot add movie, list is full" << endl;
return;
}
++last_movie_index;
movies[last_movie_index] = m;
}
void PrintAll() {
for (int i = 0; i < movie_count; i++) {
movies[last_movie_index].PrintMovie();
}
}
};
void ReadMovieFile(vector<string> &movies);
void LoadMovies();
enum MovieSortOrder
{
BY_YEAR = 0,
BY_NAME = 1,
BY_VOTES = 2
};
int main()
{
LoadMovies();
// TODO:
// You need to implement the Movie and MovieList classes and
// the methods below so that the program will produce
// the output described in the assignment.
//
// Once you have implemented everything, you should be able
// to simply uncomment the code below and run the program.
MovieList *movies = LoadMovies();
// // test methods for the Movie and MovieList classes
//PrintAllMoviesMadeInYear(movies, 1984);
//PrintAllMoviesWithStartLetter(movies, 'B');
//PrintAllTopNMovies(movies, 5);
//delete movies;
return 0;
}
void LoadMovies()
{
vector<string> movies;
ReadMovieFile(movies);
string name;
int year;
double rating;
int votes;
for (int i = 0; i < movies.size(); i++)
{
istringstream input_string(movies[i]);
getline(input_string, name, '\t');
input_string >> year >> rating >> votes;
Movie movie (name, year, votes, rating);
movie.PrintMovie();
}
}
Now where I'm stuck at is where the professor asks me to modify the LoadMovies in the prompt and turn it into a pointer. I'm drawing blanks. Also for some reason if I try to compile it says:
C:\Users\Andy\Documents\C++ Homework\MovieStatisticsProgram\MovieStatsProgram.cpp:163: error: void value not ignored as it ought to be
MovieList *movies = LoadMovies();
^
The order of your constructor is wrong
MovieList(int size) {
movies = new int[movies_size]; // movies_size hasn't been initialized yet!
movies_size = size;
last_movie_index = -1;
}
It should be
MovieList(int size)
: movies_size{size}, movies{new int[size]}, last_movie_index{0}
{}
Though as #ScottMcP-MVP noted your array should be
Movie* movie;
So your constuctor would be
MovieList(int size)
: movies_size{size}, movies{new Movie[size]}, last_movie_index{0}
{}
Some advice for getting started on the remaining functions
Length function will return how many are current used from last_movie_index.
IsFull will check if last_movie_index == movies_size - 1
Add will need to use last_movie_index to figure out what element in your array to store the movie.
PrintAll will have to iterate from [0] to [movie_count] and print out each element.
Your Add function would look something like
void MovieList::Add(Movie const& m)
{
if (IsFull())
{
std::cout << "Cannot add movie, list is full" << std::endl;
return;
}
movies[last_movie_index] = m; // assigns a copy to your array
++last_movie_index; // Increment the movie index
}

How to sort custom class objects iside of an array

I am wondering how to sort an array that contains objects of a custom class. I am trying to apply different sorting algorithms but in the swapping something goes wrong.
Here is my Code:
class RaceCar
{
private:
char* _brand;
char* _model;
double _price;
int _horse_power;
public:
//Other code
RaceCar(const RaceCar& rc):_price(rc._price), _horse_power(rc._horse_power)
{
_brand = new char[strlen(rc._brand)+1];
strcpy(_brand, rc._brand);
_model = new char[strlen(rc._model)+1];
strcpy(_model,rc._model);
}
RaceCar& operator=(const RaceCar& rc)
{
if(this != &rc)
{
delete _brand;
delete _model;
_brand = new char[strlen(rc._brand)+1];
strcpy(_brand, rc._brand);
_model = new char[strlen(rc._model)+1];
strcpy(_model, rc._model);
_price = rc._price;
_horse_power = rc._horse_power;
}
return *this;
}
bool operator<(const RaceCar& rc)
{
return (this->_price/this->_horse_power) > (rc._price/rc._horse_power);
}
//Other code
};
And this is the class that contains an array of RaceCars. I am trying to implement SortCars() method that orders the RaceCar objects inside the array of cars:
class RaceCarGarage
{
private:
RaceCar* _cars;
int _max_cars;
int _curr_occupied;
public:
RaceCarGarage():_cars(NULL), _max_cars(0),_curr_occupied(0){}
RaceCarGarage(const RaceCar& car, int max_cars)
:_max_cars(max_cars), _curr_occupied(0)
{
_cars = new RaceCar[_max_cars];
}
~RaceCarGarage()
{
delete _cars;
}
void AddCar(const RaceCar& car)
{
if(_curr_occupied < _max_cars)
{
_cars[_curr_occupied] = car;
_curr_occupied += 1;
}
}
void DisplayCars()
{
if(_curr_occupied > 0)
{
for(int i=0 ; i<_curr_occupied ; i++)
{
cout<<(i+1)<<". ";
(_cars+i)->Display();
}
}
}
void SortCars()
{
if(_curr_occupied > 1)
{
for(int i=0 ; i<_curr_occupied ; i++)
{
for(int j = i+1 ; j<_curr_occupied ; j++)
{
if(_cars[j]<_cars[i])
{
RaceCar buffer = _cars[i];
_cars[i] = _cars[j];
_cars[j] = buffer;
}
}
}
}
}
};
The problem with the swapping is that you use the traditional way to do:
temp = a // operator=
a = b // operator=
b = temp; // operator=
However, if you write:
RaceCar temp = a; // Copy constructor gets called (see comment on standard)
a = b; // operator=
b = temp; // operator=
The default copy constructor, just copies member by member, so just copies your pointer. So at the end, your temp and your will try to delete twice the same object pointed to.
Remark on assignment initializer :
For a type T, a statement in form T a = b; is an initializer.
The ISO standard C++ in section 12.6.1 point 1 explains "a single assignment-expression can be specified as an initializer using the = form of initialization. Either direct-initialization semantics or copy-initialization semantics apply;"

Assign value using overloaded subscript operator

I am trying to create custom array indexed from 1 using subscript operator. Getting value works fine, but I have no clue, why assign using subscript operator doesn't work.
class CEntry {
public:
CKey key;
CValue val;
CEntry(const CKey& key, const CValue& val) {
this->key = key;
this->val = val;
}
CEntry& operator= (const CEntry& b) {
*this = b;
return *this;
};
};
...
class EntriesArray {
public:
CEntry **entries;
int length;
EntriesArray(int length) {
this->length = length;
entries = new CEntry*[length];
int i;
for (i = 0; i < length + 1; i++) {
entries[i] = NULL;
}
};
CEntry& operator[] (const int index) {
if (index < 1 || index > length) {
throw ArrayOutOfBounds();
}
return *entries[index - 1];
};
};
Constructs array this way
EntriesArray a(5);
This works
a.entries[0] = new CEntry(CKey(1), CValue(1));
cout << a[1].val.value << endl;
This doesn't work
a[1] = new CEntry(CKey(1), CValue(1));
EDIT:
Using
CEntry *operator=( CEntry *orig)
it compiles okey, but gdb stops at
No memory available to program now: unsafe to call malloc warning: Unable to restore previously selected frame
with backtrace
Program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: KERN_PROTECTION_FAILURE at address: 0x00007fff5f3ffff8
0x00000001000013c8 in CEntry::operator= (this=0x0, orig=0x1001008d0) at /Users/seal/Desktop/efa du2_pokus2/efa du2_pokus2/main.cpp:20
20 /Users/seal/Desktop/efa du2_pokus2/efa du2_pokus2/main.cpp: No such file or directory.
in /Users/seal/Desktop/efa du2_pokus2/efa du2_pokus2/main.cpp
At first... This:
CEntry& operator= (const CEntry& b) {
*this = b;
return *this;
};
Shouldn't work (this should result in recursive call of operator=).
The second thing is that you're trying to assign CEntry * to CEntry, this would work if you had CEntry *operator=( CEntry *orig), but I think this is bad coding practice.
This question may be related to this one.
I tried to fix your code; I believe that this is what you were trying to do:
(tested this code on g++ 5.3.0)
#include <iostream>
#include <stdexcept>
#include <string>
// Some implementation for CKey and CValue:
typedef int CKey;
struct CValue {
int value;
CValue(int value=0) : value(value) {}
};
class CEntry {
public:
CKey key;
CValue val;
CEntry(): key(0), val(0) {}
CEntry(const CKey& key, const CValue& val): key(key), val(val) {}
CEntry& operator= (const CEntry& b) {
this->key = b.key;
this->val = b.val;
return *this;
};
};
class EntriesArray {
public:
CEntry *entries;
int length;
EntriesArray(int length) {
this->length = length;
entries = new CEntry[length];
};
CEntry& operator[] (const int index) {
if (index < 1 || index > length) {
throw std::domain_error("out of bounds!");
}
return entries[index - 1];
};
};
int main(int argc, char* argv[]) {
using namespace std;
EntriesArray a(5);
// This works
a.entries[0] = CEntry(CKey(1), CValue(1));
cout << a[1].val.value << endl;
// This doesn't work
a[1] = CEntry(CKey(2), CValue(2));
cout << a[1].val.value << endl;
}
Also you might want to use a[1] as a[1].val.value e.g.:
cout << a[1] << endl;
To do this just add to this line to cEntry:
operator int() { return val.value; }
I hope it helps.
You could try replacing
CEntry& operator[] (const int index) {
if (index < 1 || index > length) {
throw ArrayOutOfBounds();
}
return *entries[index - 1];
};
with
void Add(const int index, CEntry *pEntry) {
if (index < 1 || index > length) {
throw ArrayOutOfBounds();
}
entries[index - 1] = pEntry;
};
but since you are now storing references to objects allocated on the heap (with new) you will need a destructor ~EntriesArray() to delete them all.
Because EntriesArray::operator[] returns a CEntry &, but new CEntry returns a CEntry *.
Perhaps you want a[1] = CEntry(CKey(1), CValue(1))? (no new.)
By the way, your current definition of CEntry::operator= will lead to a stack overflow.
This
return *entries[index - 1];
dereferences a NULL pointer.
You want the pointer itself to be overwritten by a[1] = new CEntry(CKey(1), CValue(1));, not the pointed-to-value.
Try this:
class EntriesArray
{
public:
int length;
CEntry **entries;
EntriesArray( int length ) : length(length), entries(new CEntry*[length]())
{
}
// defaulted special member functions are inappropriate for this class
EntriesArray( const EntriesArray& ); // need custom copy-constructor
~EntriesArray(); // need custom destructor
EntriesArray& operator=(const EntriesArray&); // need custom assignment-operator
CEntry*& operator[] (const int index) {
if (index < 1 || index > length) {
throw ArrayOutOfBounds();
}
return entries[index - 1];
}
};
Further to my comment above:
To make it work with writing new values, you probably need something like this
(I haven't double checked for off by one or ptr vs reference stuff)
CEntry& operator[] (const int index) {
if (index < 1) {
throw ArrayOutOfBounds();
}
// Add default elements between the current end of the list and the
// non existent entry we just selected.
//
for(int i = length; i < index; i++)
{
// BUG is here.
// We don't actually know how "entries" was allocated, so we can't
// assume we can just add to it.
// We'd need to try to resize entries before coming into this loop.
// (anyone remember realloc()? ;-)
entries[i] = new CEntry();
}
return *entries[index - 1];
};