Chris Condy
Chris Condy

Reputation: 636

std::list iterator

The following code instead of returning a pointer back to an audioResource it returns something else which is invalid, i've gone through with a debugger and the problem is with this line

return *list_it;

Here is my function:

AudioResource* AudioManager::getResource(const unsigned int ID)
{
    std::list<AudioResource*>::iterator list_it;
    for(list_it = m_resources.begin(); list_it!= m_resources.end(); list_it++)
    {
        if((*list_it)->getID()==ID)
            {
std::cout<<*(*list_it)->getFileName();
            return *list_it;
        }
    }
    return nullptr;
}

O and I have tried putting it as (*list_it) but i got the same results =s

How it is populated...

Resource* AudioManager::addResource(const unsigned int ID, 
      const std::string fileName,  const unsigned int scope,
      const std::string type)
{
     AudioResource* temp;
     if(type == "AUDIO_TYPE_SAMPLE")
     {
          temp = new AudioResource(ID,fileName,scope,
                      RESOURCE_AUDIO,AUDIO_TYPE_SAMPLE);
          m_resources.push_back(temp);
     }
     else if(type == "AUDIO_TYPE_STREAM")
     {
          temp = new AudioResource(ID,fileName,scope,
                    RESOURCE_AUDIO,AUDIO_TYPE_STREAM);
          m_resources.push_back(temp);
     }

     return temp;
}

call to get resource

cout<<AudioManager::getInstance()->getResource(IDnum)->getFileName();

Upvotes: 0

Views: 8229

Answers (2)

Xeo
Xeo

Reputation: 131887

You return nullptr in case the ID doesn't exist, but you never check against it at the call site, which will give you a null pointer access if the ID doesn't exist and which will likely create problems.

AudioManager::getInstance()->getResource(IDnum)->getFileName();

Change that to

AudioResource* res = AudioManager::getInstance()->getResource(IDnum);
if(res)
  std::cout << res->getFileName();

Upvotes: 1

hmjd
hmjd

Reputation: 122011

If type is neither of the two values an uninitialized pointer is added to m_resources:

AudioResource* temp;
if(type == "AUDIO_TYPE_SAMPLE")
{
    temp = new AudioResource(ID,fileName,scope,RESOURCE_AUDIO,AUDIO_TYPE_SAMPLE);
}
else if(type == "AUDIO_TYPE_STREAM")
{
    temp = new AudioResource(ID,fileName,scope,RESOURCE_AUDIO,AUDIO_TYPE_STREAM);
}
m_resources.push_back(temp);

Initialize temp to NULL and only add to m_resources if temp != NULL.

Also, the function returns the same uninitialized pointer.

Upvotes: 2

Related Questions