Value of array member changes illogically

2019-08-23 12:48发布

问题:

I noticed once that when I declare an array,

int arr[10];

after a while the value of array member changes although nothing affects it during a period. Then I made use of dynamic allocation with "new" and the problem solved. I thought that everything should be declared dynamically. But this shouldnt be true. What may be a logical reason?

回答1:

Could be number of reasons:

  • Initialize your array member if it is on local storage or it contains any random value if you didn't.
  • You probably overwrite the bounds of some other array in the same function which corrupts the stack and your array.
  • You corrupt the stack in some magical way.