0

Visual C++, Microsoft Visual Studio 2010 Express:

Access from this malloc works:

float* block  = (float *)_aligned_malloc(32 * sizeof(float), CACHE_ALIGNMENT);
block[0] = (float)30;  // I work fine.

But when it is inside this class, it does not work:

class Test
{
    private:
        //static const int numberOfElements = 1024;

    public:
        float* block1;
        float* block2;

    // Constructor
        Test::Test(int nElements)
        {
            float* block1 = (float *)_aligned_malloc(nElements * sizeof(float), CACHE_ALIGNMENT);
            float* block2 = (float *)_aligned_malloc(nElements * sizeof(float), CACHE_ALIGNMENT);
        }
    // Destructor
        Test::~Test(void) 
        {
            _aligned_free(block1);
            _aligned_free(block2);
        }
};

...

Test testClass = Test(32); 
testClass.block1[0] = (float)30;  // Access violation!

...

Or if declared as a pointer, the same thing (this is how I first tried it):

Test* testClass = new Test(32);
testClass.block1[0] = (float)30;  // Access violation!

What am I doing wrong in terms of accessing the values when the float* is define inside a class? Is the problem something else?

kapa
  • 77,694
  • 21
  • 158
  • 175

2 Answers2

4

You assign to the variables local to constructor, not member variables. Try something like

    Test::Test(int nElements)
    {
        block1 = (float *)_aligned_malloc(nElements * sizeof(float), CACHE_ALIGNMENT);
        block2 = (float *)_aligned_malloc(nElements * sizeof(float), CACHE_ALIGNMENT);
    }

and check the values to make sure allocation succeeded.

Michael Krelin - hacker
  • 138,757
  • 24
  • 193
  • 173
0

The declarations of the variables block1 and block2 local to the constructor shadow the member variables block1 and block2.

With g++ you can get a warning for this with -Wshadow option. With Visual Studio I'm afraid there is no option to warn when a variable shadows another one.

ouah
  • 142,963
  • 15
  • 272
  • 331