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 long
s.
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 (somem1[0]
cannot refer lower half-word ofmem1
,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 char
s necessary store int
) 4. thus, store 2 int
s, 1 needs allocate 2*sizeof(int)
, or 8 bytes.
in hypothetical world long
basic unit of memory (and sizeof(long) == 8
), storing 2 int
s require either packing or 16 bytes allocated, that’s not way c works.
Comments
Post a Comment