2

So I have a struct

struct float3
{
    float x, y, z;
};

and I am trying to create a function to take the x,y,z values and map them to keys 0, 1, 2 for their respective dimension. I wrote the code below but it throws a bad alloc_exception. It appears like I'm running out of memory.

KdTree::float2map(std::vector<float3>& data)
    {    
       std::vector<std::map<int, float> > m_pnts;
       int cnt = 0;
       for(int i = 0; i = data.size(); i++)
          {
             std::map<int, float> tmp;
             tmp.insert(std::make_pair(0, data[i].x));
             tmp.insert(std::make_pair(1, data[i].y));
             tmp.insert(std::make_pair(2, data[i].z));

             m_pnts.push_back(tmp);
             std::cout << m_pnts.size() << std::endl;
            }

       }

       return m_pnts;
    }

I'm still fairly new to C++ so I'm sure there are many other ways to do this or to optimize this approach. The problem is I have to do this one 33,914,095 float3s and I can't think of another way to achieve this. Any help would be greatly appreciated.

p0ps1c1e
  • 176
  • 2
  • 2
  • 14

1 Answers1

1

Look at this line of code:

for(int i = 0; i = data.size(); i++)

You are setting i to data.size() in the condition of the for statement. This will cause an out of bounds access because data.size() will become the index to data vector whose elements are indexed from 0 to data.size() - 1.

That was probably not your intention. Use a proper condition in the for loop. It should be:

for(int i = 0; i < data.size(); i++)

Or better still, use a range-based for loop which help in avoiding such bugs:

for(const auto& ele: data)
{
    std::map<int, float> tmp;
    tmp.insert(std::make_pair(0, ele.x));
    tmp.insert(std::make_pair(1, ele.y));
    tmp.insert(std::make_pair(2, ele.z));
    m_pnts.push_back(tmp);
    std::cout << m_pnts.size() << std::endl;
}        
P.W
  • 26,289
  • 6
  • 39
  • 76
  • Opps... thanks for catching that. However, it doesn't seem to be the source of my problem. My program seems to only be able to map up to 4,194,304 points until it throws bad_alloc. I'm not sure why as I have 16GB of memory. I'm using codeblocks GCC compiler. I realized first I was using a 32 bit compiler so I switched it to 64 bit but its still throwing bad_alloc in the same place. I feel like I'm missing something perhaps. – p0ps1c1e Feb 14 '19 at 22:04