Home > Back-end >  Dynamic allocation of float matrix causes Access violation writing location error
Dynamic allocation of float matrix causes Access violation writing location error

Time:12-21

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!

CodePudding user response:

Here are the problems:

  • Casting of a float* to a float**
  • Didn't declare the matrix correctly (should be new float*[matrix_height])
#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;
}

CodePudding user response:

C style for your code (I had to guess some variable names, I hope you can do better, since you know what your code should be doing).

#include <iostream>
#include <vector>

int main()
{
    // datastructure sizes use std::size_t
    static constexpr std::size_t maxIteration{ 30ul }; // smaller number for demo
    static constexpr std::size_t dimensions{ 2ul };

    // no need to use `hungarian notation` name things after what they are (not how they are implemented).
    // this line alone allocates all data and sets it to 0.0f
    std::vector<std::vector<float>> point_data(dimensions, std::vector<float>(maxIteration, 0.0f));

    // and use range based for loops if you can
    // example of setting all values to 1.0f
    for (auto& dimension : point_data) // dimensions
    {
        for (auto& value : dimension) // maxIteration
        {
            value = 1.0f; // 
            std::cout << value << " ";
        }
        std::cout << "\n";
    }

    return 0;
}
  • Related