I have played a little bit with C and written the following code:
#include<stdio.h>
#include<stdlib.h>
int main() {
char* value = malloc(5 * sizeof(char));
int vect[3];
printf("%d\n", value[135151]);
int i, count = 0;
for(i = 0; i < 135152; i++) {
if(value[i]) {
count++;
printf("position is %d, value is %d and i change it with 42\n", i, value[i]);
value[i] = 42;
vect[count - 1] = i;
}
}
printf("count is %d\n", count);
printf("pointer is at location %p\n", value);
printf("changed values are %d %d %d\n", value[vect[0]], value[vect[1]],
value[vect[2]]);
return 0;
}
After several tries, on my laptop, I have found out that if I print value[135152] I get segfault, and if I print value[135151] I get 0 at stdout.
After that, I was curious to find if there are nonzero values in this interval, and 3 nonzero values where shown.
After that, I tried to modify them all to be 42 (I forgot to mention that at many program executions, 20+, even if the vector value was shown at a different location, such as 0xbe7010 or 0x828010, the same nonzero values at the same position remained, which made me understand that the pointer address is virtual (but the location is the same)).
After, I have modified those values, I printed them in the end just to be sure, and they showed 42 all 3 of them. But, at another program execution, the previous values were shown, just like I hadn't modify that memory zone.
I will give you 3 consecutive outputs of mine:
0
position is 24, value is -31 and i change it with 42
position is 25, value is 15 and i change it with 42
position is 26, value is 2 and i change it with 42
count is 3
pointer is at location 0x21bb010
changed values are 42 42 42
0
position is 24, value is -31 and i change it with 42
position is 25, value is 15 and i change it with 42
position is 26, value is 2 and i change it with 42
count is 3
pointer is at location 0x20d1010
changed values are 42 42 42
0
position is 24, value is -31 and i change it with 42
position is 25, value is 15 and i change it with 42
position is 26, value is 2 and i change it with 42
count is 3
pointer is at location 0x19d0010
changed values are 42 42 42
Could you please tell me why those values persist even after changing?
And also, why is the pointer address changing, but memory zone is the same? (I suspect there is a bijective function between the physical and virtual memory in C that changes every time I execute the program).
Thank you for your help and sorry for this Wall of Text!