0

Suppose the following program is run on an x86_64 system:

int main() {
    //sizeof(int) == 4
    //sizeof(int*) == 8
    //sizeof(long) == 8

    // I would like 2 distinct memory locations to hold these two integers
    int* mem1 = (int*)malloc(2 * sizeof(int));
    mem1[0] = 1;
    mem1[1] = 2;

    //I would like 1 distinct memory location to hold this one long
    long* mem2 = (long*)malloc(1 * sizeof(long));
    mem2[0] = 3;

    free(mem1);
    free(mem2);
    return 0;
}

Since malloc receives a number of bytes to allocate, both calls to malloc look exactly the same. How does malloc know to actually allocate 16 bytes to store the two integer array and only to allocate 8 bytes for the one long?

Edit for clarity: Based on the following assumptions, storing these two different arrays will require a different amount of space for each. However, malloc appears to reserve the same amount of space each time in this program. Yet, arrays sizes are correctly determined for arrays of datatypes of different lengths than longs.

Can someone help me identify a flaw in this understanding of the memory, or point to something that malloc / libc is doing in the background? Here are the assumptions I'm operating on

  • At each memory address on this system, a maximum of one long can be stored in it
  • mem[idx] refers to the address of mem plus the offset of idx, and that address cannot point to data in the middle of another item in memory (so mem1[0] cannot refer to the lower half-word of mem1 and mem1[1] can't then refer to the high word)
  • When an array of integers are made, two integers are not packed on this system into one long
4

4 回答 4

7

malloc 如何区分占用相同空间的不同类型?

它没有。

由于 malloc 接收要分配的字节数,因此对 malloc 的两次调用看起来完全相同。malloc 如何知道实际分配 16 个字节来存储两个整数数组,而只为一个 long 分配 8 个字节

它只能使用您传递给它的大小作为它的参数。但是,您的示例和/或理解存在缺陷-使用指定的sizeof值,两个调用都将分配 8 个字节。(也就是说,2 * sizeof(int)这是2 * 4,并且sizeof(long),这是1 * 8。)

于 2013-08-23T20:58:41.603 回答
2

提问者很困惑,因为他没有意识到这char是 C 中内存的基本单位。在他的平台上,sizeof(int)char存储 an 所需的 s的数量int)是 4。因此,要存储两个ints,需要分配一个2*sizeof(int),或 8 个字节。

在假设的世界中long,内存的基本单元(和sizeof(long) == 8)是,存储两个ints 确实需要打包或分配 16 个字节,但这不是 C 的工作方式。

于 2013-08-23T22:43:26.353 回答
1

malloc doesn't,但是当您调用mem[0]mem[1]编译器知道什么是mem( int *mem) 类型时,因此当您调用mem[1]它时,它将知道要增加多少mem指针以访问该数组的第二个元素。区别发生在编译器方面。

于 2013-08-26T14:41:14.977 回答
1

你总是可以用一些printf陈述来测试你的论文。对于您的示例,请使用:

    printf("\nsizeof int is %d, long is %d", sizeof(int), sizeof(long));

你会看到:2*sizeof(int) == 1*sizeof(long).

于 2013-08-23T22:03:29.490 回答