C program - different behaviour on different machines. Memory allocation problem?
I have a C program giving different results when run on two machines.
On the first machine (Linux Ubuntu, gcc compiler v 4.4.3, 64bit, 4GB memory) it seems to work fine and gives reasonable results (actually this is the machine on which it has been mainly developed).
On the second machine (Mac OSX 10.5.8, gcc compiler v 4.4.5, 32bit, 2GB memory) the results appear to be nonsense.
In particular, there is an array A filled in during a FOR cycle in which each term A[i] depends on A[i-1]. I have found out that after about 4000 steps my machine starts to forget the A[i-1] values and then calculates nonsense.
Even more bizarre to me, the problem disappears if in the initial list of variable declaration of the function I add another fictitious array, which I don't even use in the program.
That is, a code with a h开发者_运维知识库eader like
...
double X[n_max];
double Y[n_max];
double A[n_max];
...
works, while
...
double X[n_max];
// double Y[n_max];
double A[n_max];
does not.
I guess there is some sort of problem in memory allocation, and that when I allocate memory for the fictitious array Y the mess is simply moved elsewhere.
I don't understand neither why my Mac seems to have no problems in overwriting data it is supposed to remember, nor why the same program is working on the Linux machine.
I hope that the problem is clear, any help is appreciated. Thank you!
Well, it is obvious that one of the X[] or A[] arrays is being indexed out of bounds. Just as a test replace all array indices by unsigned or size_t, recompile and run under a debugger. The program will probably segfault.
First - you certainly have a bug in your program, and turning up the level of compiler warnings, or running with valgrind may help find it.
The memory layout is naturally different, because of different compilers and CPU architecture, my first guess would be that the issue is related to 64bit vs 32bit architecture (impacting pointer sizes, memory alignement, etc.).
精彩评论