c - How does malloc distinguish between different types that both take up the same space? -


suppose following program run on x86_64 system:

int main() {     //sizeof(int) == 4     //sizeof(int*) == 8     //sizeof(long) == 8      // 2 distinct memory locations hold these 2 integers     int* mem1 = (int*)malloc(2 * sizeof(int));     mem1[0] = 1;     mem1[1] = 2;      //i 1 distinct memory location hold 1 long     long* mem2 = (long*)malloc(1 * sizeof(long));     mem2[0] = 3;      free(mem1);     free(mem2);     return 0; } 

since malloc receives number of bytes allocate, both calls malloc same. how malloc know allocate 16 bytes store 2 integer array , allocate 8 bytes 1 long?

edit clarity: based on following assumptions, storing these 2 different arrays require different amount of space each. however, malloc appears reserve same amount of space each time in program. yet, arrays sizes correctly determined arrays of datatypes of different lengths longs.

can me identify flaw in understanding of memory, or point malloc / libc doing in background? here assumptions i'm operating on

  • at each memory address on system, maximum of 1 long can stored in it
  • mem[idx] refers address of mem plus offset of idx, , address cannot point data in middle of item in memory (so mem1[0] cannot refer lower half-word of mem1 , mem1[1] can't refer high word)
  • when array of integers made, 2 integers not packed on system 1 long

the questioner confused because didn’t realize char basic unit of memory in c. on platform, sizeof(int) (which number of chars necessary store int) 4. thus, store 2 ints, 1 needs allocate 2*sizeof(int), or 8 bytes.

in hypothetical world long basic unit of memory (and sizeof(long) == 8), storing 2 ints require either packing or 16 bytes allocated, that’s not way c works.


Comments

Popular posts from this blog

java - Run a .jar on Heroku -

java - Jtable duplicate Rows -

validation - How to pass paramaters like unix into windows batch file -