I have a simple code:
#include <stdio.h>
#include <stdlib.h>
int main(void){
char *str = (char *) malloc(4*sizeof(char));
int i;
for(i = 0; i < 64; i ++)
printf("%d, %ld, %d, %c\n", i, (long) &(str[i]), (int) str[i], str[i]);
return 0;
}
I allocate a memory into str
using malloc()
which is available to save 4 letters in str[0], ..., str[3]
. I know that malloc()
does not initialize its memory while calloc()
does.
This program prints str[i]
with i
, address of str[i]
, value of str[i]
, letter of str[i]
, in order. (I use 64-bits Ubuntu, hence address is long
type.)
As expected, addresses are quite different for every time I run the program. But I wonder that why str[24]
, str[25]
, and str[26]
are -31, 15, 2, repectively, and other values are all 0 as you can see below:
(Note that without option -O0 gives same result.)
How can memory has same sequence (0,0,...,0,-31,15,2,0,0,...) even though only first four 0s in that sequence are allocated and others are out of care?