开发者

Dynamic 2D array losing second dimension

开发者 https://www.devze.com 2023-03-04 15:50 出处:网络
I have a dynamically allocated, 2D array that is being populated within a pair of for loops.For some reason by the end of the for loops all of the elements are in inaccessible memory.

I have a dynamically allocated, 2D array that is being populated within a pair of for loops. For some reason by the end of the for loops all of the elements are in inaccessible memory.

/*************Start Positive Phase*************************/
double *posHidActivations = new double[FEATURES];
memset(posHidActivations, 0, sizeof(double)*FEATURES);

double *posVisActivations = new double[m_NumRatings];
memset(posVisActivations, 0, sizeof(double)*m_NumRatings);


double **posProducts = new double*[FEATURES];
for(int i=0; i<FEATURES; i++)
   posProducts[i] = new double[m_NumRatings];
for(int i=0; i<FEATURES; i++)
   for(int j=0; j<m_NumRatings; j++)
      posProducts[i][j] = 0;
/* manually verified elements are valid and 
   initialized to 0 with gdb */

// for each hidden node
for(int j=0; j<FEATURES; j++)
{   
   // sum up inputs from the visible layer
   for(int i=0; i<m_NumRatings; i++)
   {   
      double input = m_VisLayer[i]*m_Weig开发者_高级运维hts[i][j];
      double prob = sigmoid(input, m_HidItemBias[j]);
      posProducts[j][i] = m_VisLayer[i]*prob;
      posVisActivations[j]+=m_VisLayer[i];   // commenting out this line fixes
      posHidActivations[j]+=prob;
   }   
   // posProducts[i][0] is valid here
}  
/* posProducts[0][0] is a segfault 
   using gdp verified that posProducts is a valid double**
   and posProducts[0] is a valid double*

Declarations for identifiers not in the previous snippit:

int m_NumRatings;

m_VisLayer = new double[m_NumRatings];

m_Weights = new double* [m_NumRatings];
for(int i=0; i<m_NumRatings; i++)
   m_Weights[i] = new double [FEATURES];

m_HidItemBias = new double[FEATURES];

'FEATURES' is a #defined constant

Edit: I forgot to mention. Later in the program is a logically identical code block using different identifiers (posProducts -> negProducts, m_VisLayer -> m_HidLayer, etc). That block does not show any of the same symptoms. I can't find any logical difference no matter how many times I compare the code.


As you note:

posVisActivations[j]+=m_VisLayer[i];   // commenting out this line fixes

The index for posVisActivations is j, which ranges from 0 to m_FEATURES, but posVisActivations is declared to be an array with m_numRatings elements.

So, you are writing past the end of the array. You probably meant to use i as the index:

posVisActivations[i]+=m_VisLayer[i];   // commenting out this line fixes

HTH.

0

精彩评论

暂无评论...
验证码 换一张
取 消