Memory malloc对char使用4个字节
我正在编写一个代码来检查如何在堆栈和堆之间管理内存。为了一门课程的工作Memory malloc对char使用4个字节,memory,alignment,malloc,Memory,Alignment,Malloc,我正在编写一个代码来检查如何在堆栈和堆之间管理内存。为了一门课程的工作 #include<stdio.h> #include<stdlib.h> #define NUM_OF_CHARS 100 // function prototype void f(void); int main() { f(); return 0; } void f(void) { char *ptr1; ptr1 = (char *) malloc(N
#include<stdio.h>
#include<stdlib.h>
#define NUM_OF_CHARS 100
// function prototype
void f(void);
int main()
{
f();
return 0;
}
void f(void)
{
char *ptr1;
ptr1 = (char *) malloc(NUM_OF_CHARS * sizeof(int));
printf("Address array 1: %016lx\n", (long)ptr1);
char *ptr2;
ptr2 = (char *) malloc(NUM_OF_CHARS * sizeof(int));
printf("Address array 2: %016lx\n", (long)ptr2);
}
我的期望是看到地址100字节的差异,但差异是416字节,当我将字符的NUM_更改为任何其他值200300时,。。。结果总是NUM_OF_CHARS*4+16,因此malloc为每个char分配4个字节,而不是一个字节加上16个字节的开销
有人能解释一下这里发生了什么吗?内存分配取决于平台/编译器。malloc唯一能确保的是,它为您的请求分配了足够的内存,仅此而已 由于以下原因,无法保证您的地址是连续的 另外,您是按整数的大小而不是按代码中的字符进行分配的。这很可能就是为什么您会看到NUM_OF_CHARS*4的差异,而剩余的差异可以归因于填充
Address array 1: 000000000209e010
Address array 2: 000000000209e1b0