I've got a peice of code which takes an an array by address (pointer) This function simply takes an array and an integer value which is its length, and prints out the elements of the array one by one.
void dumpInts(int *array, int count, int hex){
int i;
for(i = 0; i < count; i++){
printf(" %*d",10,array[i]);
}
The above code is highly simplified, Here is the rest of the code. Its not that large.
#include <stdio.h>
#include <stdlib.h>
int LAST = -1059786739;
int FIRST = -559038737;
//Input is a series of integers read in from stdin separated by whitespace
void dumpInts(int *array, int count, int hex);
void initArray(int *array, int size);
int main(){
int bufsiz ;
if(scanf("%d",&bufsiz) < 1){
fprintf(stderr,"CAN\'T READ BUFSIZ\n");
return 1;
}
if(bufsiz < 1){
fprintf(stderr,"BAD BUFSIZ=%d\n",bufsiz);
return 1;
}
bufsiz+=2;
int *array = (int *)malloc((size_t)bufsiz);
if(array == NULL){
fprintf(stderr,"NO MORE MEM\n");
return 1;
}
array[0] = FIRST;
array[bufsiz-1] = LAST;
initArray(array,bufsiz);
dumpInts(array,bufsiz,0);
dumpInts(array,bufsiz,1);
return 0;
}
void initArray(int *array, int size){
int i;
for(i = 1; i < size - 1; i++){
array[i] = i;
}
}
void dumpInts(int *array, int count, int hex){
int i;
for(i = 0; i < count; i++){
printf(" %*d",10,array[i]);
}
Here's the thing. When The size of the array is under 7, it works great. Check out this snippet from my terminal:
-559038737 1 2 3 4 -1059786739
Suddenly though, when the size surpasses 7, the last element gets overwritten and all of the following memory is set to random values, but the 7'th element is always set to the same thing... 1041
Below is an array of size 8
-559038737 1 2 3 4 5 1041 0 892677408 942878777
Now Before I go any further, I feel I should exert that I did spend time carefully narrowing down EXACTLY WHERE the array is clobbered. Before it enters the function it is what I expect it to be, as soon as the first loop prints, the array is clobbered.
Okay so this is where it gets weird. I SSHed into my university's linux machine, and ran my code. No clobber, the array is just fine.
Comparison below for size 7
mine:
-559038737 1 2 3 4 5 1041
university:
-559038737 1 2 3 4 5 -1059786739
I am about to reboot my machine....
*Just rebooted, same problem persists... Same number too... Same size...
Also, when I compile the code on the university computer and copy it to my machine, array is clobbered still. Not so when I compile it on my machine.
Both my machine and the university machine are unix based systems, Running linux.
What the hell is going on here?!
This doesn't make any sense. I'm passing the address of the array in memory, so I don't expect the stack to have anything to do with this?