0
int main()
{
    int n = 3;
    int a[n] = {1,2,3};

    ...
    in middle of code, value of n can be increased by 10 so I want to have check before cout otherwise       a[10] is out of bound.  
    ...

    cout<<a[n-1];
    return 0;
}

To fix above issue, I simply put one if check.

Corrected code:

int main()
{
    int n = 3;
    int a[n] = {1,2,3};
    ...

    In middle of code, value of n can be increased by 10 so I want to have check before cout otherwise       a[10] is out of bound.   
    ...
    if(n<= 3)
    {
         cout<<a[n-1];    
    }
    return 0;
}

Is there any other way to avoid Out of Bound Memory Access

I tried to use if check on the basis of size.

mch
  • 9,424
  • 2
  • 28
  • 42
sur
  • 1
  • 1
  • 1
    `int n = 3; int a[n] = {1,2,3};` -- This is not valid C++ code. Array dimensions must be specified by a constant expression, not a runtime variable. You should be using `std::vector` if you want a resizable array. – PaulMcKenzie Nov 29 '22 at 08:26
  • Note that your arrays are variable-length arrays, and [C++ doesn't really have such arrays](https://stackoverflow.com/questions/1887097/why-arent-variable-length-arrays-part-of-the-c-standard). – Some programmer dude Nov 29 '22 at 08:26
  • And it's your responsibility as the programmer to make sure your code don't access arrays or vectors out of bounds. You do it by adding conditions to check for that. Or, as mentioned, use a vector that you can actually resize dynamically. – Some programmer dude Nov 29 '22 at 08:27
  • `if (n <= 3) cout << a[n-1];` seems like the correct way to check for out of bounds access (assuming you array does have a size of 3). Perhaps you should show what the other way you tried was, if you really want help with that. – john Nov 29 '22 at 08:27
  • Thank you so much. @PaulMcKenzie and other developers. I'll prefer vector. – sur Nov 29 '22 at 08:34
  • @john Instead of if condition on fixed number 3, can I use if condition with sizeof array. just like below. if (n <= (sizeof(a) / sizeof(int))) { cout< – sur Nov 29 '22 at 08:41
  • @sur It would be correct for a legal C++ array, but as others have pointed out above you do not have a legal C++ array,, so I don't know what the answer is. – john Nov 29 '22 at 08:42

1 Answers1

0
int a[n] = {1,2,3};

could to be

a[0] = 1
a[1] = 2
a[2] = 3

if n is menor or igual to -1, or mayor or igual to 3, you’ll have an excess of memory.

Before to read a[n] you can check it out:

if ( 0 >= n & n < 3)
{
  // ....you can read a[n] 
}
Davide
  • 1
  • 1