c++mfcheap-memorydynamic-arraysaccess-violation

Dynamic allocation of float matrix causes Access violation writing location error


I've received the source code of an MFC application, but when I start it I get an access violation writing location error.

Here below the VS project General configuration: Project configuration

I cannot share the full source code, but the culprit lines are the followings:

#include <iostream>

using namespace std;

int main()
{
    float** ppfPoints[2];
    int maxIteration = 300000;
    for (int i = 0; i < 2; i++)
    {
        ppfPoints[i] = (float**)new float[maxIteration];
        for (int j = 0; j < maxIteration; j++)
        {
            ppfPoints[i][j] = new float[3];
            cout<<j<<" ";
        }
    }
    
    return 0;
}

If I run it on onlinegdb (uncommenting the print) the code stops while printing the value 151479. The fun fact (at least for me) is that if I change the maxIteration value to 50000 the program stops at the value 26598.

In any case onlinegdb says "...Program finished with exit code 0", while on my MSVC compiled application I have the previously mentioned error.

Could anyone help me pointing out where the error is? Thank you in advance!


Solution

  • Here are the problems:

    #include <iostream>
    
    using namespace std;
    
    int main()
    {
        float** ppfPoints = new float*[2]; // array (pointers) of array (pointers) of floats = (float**)
        int maxIteration = 300000;
        for (int i = 0; i < 2; i++)
        {
            ppfPoints[i] = new float[maxIteration]; // returns a pointer to an array of float (float*)
            for (int j = 0; j < maxIteration; j++)
            {
                ppfPoints[i][j] = 0.f; // a float (float)
                cout<<j<<" ";
            }
        }
        
        return 0;
    }