Since you are interesting in knowing the addresses returned by malloc()
, you should make sure you are printing them properly. By "properly", I mean that you should use the right format specifier for printf()
to print addresses. Why are you using "%u"
for one and "%d"
for another?
You should use "%p"
for printing pointers. This is also one of the rare cases where you need a cast in C: because printf()
is a variadic function, the compiler can't tell that the pointers you're passing as an argument to it need to be of the type void *
or not.
Also, you shouldn't cast the return value of malloc()
.
Having fixed the above, the program is:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char **stringArr;
int size=4, i;
stringArr = malloc(size * sizeof *stringArr);
for (i=0; i < size; i++)
stringArr[i] = malloc(10 * sizeof *stringArr[i]);
strcpy(stringArr[0], "abcdefgh");
strcpy(stringArr[1], "good-luck");
strcpy(stringArr[2], "mully");
strcpy(stringArr[3], "stam");
for (i=0; i<size; i++) {
printf("%s\n", stringArr[i]);
printf("%p %p\n", (void *)(&stringArr[i]), (void *)(stringArr[i]));
}
return 0;
}
and I get the following output when I run it:
abcdefgh
0x100100080 0x1001000a0
good-luck
0x100100088 0x1001000b0
mully
0x100100090 0x1001000c0
stam
0x100100098 0x1001000d0
On my computer, char **
pointers are 8 bytes long, so &stringArr[i+1]
is at 8 bytes greater than &stringArr[i]
. This is guaranteed by the standard: If you malloc()
some space, that space is contiguous. You allocated space for 4 pointers, and the addresses of those four pointers are next to each other. You can see that more clearly by doing:
printf("%d\n", (int)(&stringArr[1] - &stringArr[0]));
This should print 1.
About the subsequent malloc()
s, since each stringArr[i]
is obtained from a separate malloc()
, the implementation is free to assign any suitable addresses to them. On my implementation, with that particular run, the addresses are all 0x10 bytes apart.
For your implementation, it seems like char **
pointers are 4 bytes long.
About your individual string's addresses, it does look like malloc()
is doing some sort of randomization (which it is allowed to do).