Question

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;
}
Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top