Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

memory allocation in C

I have a question regarding memory allocation order. In the following code I allocate in a loop 4 strings. But when I print the addresses they don't seem to be allocated one after the other... Am I doing something wrong or is it some sort of defense mechanism implemented by the OS to prevent possible buffer overflows? (I use Windows Vista).

Thank you.

 char **stringArr;
 int size=4, i;

 stringArr=(char**)malloc(size*sizeof(char*));
 for (i=0; i<size; i++)
    stringArr[i]=(char*)malloc(10*sizeof(char));

 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("%d  %u\n\n", &(stringArr[i]), stringArr[i]);
 }

Output:

abcdefgh 9650064 9650128

good-luck 9650068 9638624

mully 9650072 9638680

stam 9650076 9638736

like image 214
thedp Avatar asked Jan 24 '10 22:01

thedp


1 Answers

Typically when you request memory through malloc(), the C runtime library will round the size of your request up to some minimum allocation size. This makes sure that:

  • the runtime library has room for its bookkeeping information
  • it's more efficient for the runtime library to manage allocated blocks that are all multiples of some size (such as 16 bytes)

However, these are implementation details and you can't really rely on any particular behaviour of malloc().

like image 175
Greg Hewgill Avatar answered Sep 30 '22 19:09

Greg Hewgill