1
int** z= new int *[5];
for (int j = 0; j < 8; j ++)
{
    z[j] = new int[5];        
}

for (int n=0; n<8; ++n)
{
    for(int m=0;m<5;++m)
    {
        int  x=n%4;
        int  y=x*wB;
        int p=(*(B+(y+m)));

        z[n][m]=p;            
    }                
}    
return z;    

throws a Bad_Acess_error at n=6, but

int** z= new int *[5];
for (int j = 0; j < 8; j ++)
{
    z[j] = new int[5];        
}

for (int n=0; n<8; ++n)
{
    for(int m=0;m<5;++m)
    {
        int  x=n%4;
        int  y=x*5;
        int p=(*(B+(y+m)));

        z[6][m]=p;            
    }            
return z;               
}

throws no error. Why? This is really weird and I can't seem to understand why this is happening. I am just typing in more text so it allows me to publish this question.

Edit: replaced variables with numbers. The numbers are just limits of the array in question. I know the second code works because the output is exactly what I expect it to be.

3
  • 1
    What is variable wB? Commented Jun 28, 2016 at 16:54
  • 1
    What is the value of wb? It also looks like you have your conditions backwards. wb shoul be the limit of the outer for loop not the inner loop. Commented Jun 28, 2016 at 16:55
  • 1
    Why j<8 and n<8? Sometimes you use wB sometimes the magic number 8. Anyway, as soon as you access an array outside its definition range, the C++ runtime is free to do anything as far as the C++ standard is concerned, including both reporting or not reporting an error. It is very likely that your second program just looks to be fine, but actually is not. Commented Jun 28, 2016 at 17:00

1 Answer 1

1

Simply put: Buffer Overrun.

int** z= new int *[5];  // Allocates space for 5 slots.

for (int j = 0;
     j < 8;   // <---- *** Assumes space for 8 slots!!!!!
     j ++)
{
    z[j] = new int[5];  // At j==6, access is outside the array.  
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. So for 2d arrays it is int** z= new int *[rowSize]; for (int j = 0; j < 8; j ++) { z[j] = new int[Column Size]; }
If you want a 2d array that is 8 x 5, you need to make the first allocation 8 instead of 5. You have created a 5x5.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.