#include<stdio.h>
#include<stdlib.h>
int main()
{
char *a = (char malloc(sizeof(char)*10);
printf("%d\n", malloc_usable_size(a) / sizeof(char));
}
我明明开辟的是 10个 char 空间为何显示的是24个char空间
我又做了个小实验
#include<stdio.h>
#include<stdlib.h>
int main()
{
int n = 41;
char *a = (char *)malloc(sizeof(char)*n);
int i;
for(i = 0; i < 24; i++){
a[i] = i;
}
for(i = 0; i < 24; i++){
printf("%d\n", a[i]);
}
printf("array is: %d, a is: %d\n",sizeof(char)*n, malloc_usable_size(a));
}
我还试过 给 a+24 处的地址赋值,但是提示空间不存在。
也试过传sizeof(char) * 24 也就是 24个直接进去,实际开辟的是24个字节的空间。
传 25,开辟的是40个字节。
这个结果表明 我确实传进去的是 sizeof(char)*10 个字节 但是实际开辟了24个字节的空间,
这是为何?