首页 > 解决方案 > 为什么 malloc 没有分配指定的内存量?

问题描述

我正在学习 C 动态内存分配,但无法弄清楚为什么malloccalloc不分配为 struct 数组指定的内存量,也不为名称 char 数组分配内存量。

代码示例:

struct spaceShip{
  long long int distance; // 8 bytes
  int numParts; // 4 bytes
  char *name; // 1 byte
}; // 13 bytes total

int main (int argc, char *argv[]){

  int amount=10;
  struct spaceShip *spaceShipArray;

  printf("size of struct spaceShip = %d bytes\n", sizeof(struct spaceShip));

  spaceShipArray = malloc(amount * sizeof(*spaceShipArray));
  printf("size of spaceShipArray = %d bytes\n", sizeof(*spaceShipArray));

  spaceShipArray[0].name = malloc(100 * sizeof(char));
  printf("size of name char array = %d \n", sizeof(spaceShipArray[0].name));

  free(spaceShipArray);

  return 0;
}

输出:

size of struct spaceShip = 16 bytes //I guess because of the pagination mechanism it takes more? 
size of spaceShipArray = 16 bytes // not ok. should be 160
size of name char array = 4 // not ok. should be 100

标签: cprintfmallocdynamic-memory-allocationsizeof

解决方案


对于要输出类型对象的初学者,size_t您必须使用转换说明符%zu。例如

printf("size of struct spaceShip = %zu bytes\n", sizeof(struct spaceShip));

这两种说法

printf("size of struct spaceShip = %zu bytes\n", sizeof(struct spaceShip));
printf("size of spaceShipArray = %zu bytes\n", sizeof(*spaceShipArray));

输出相同的值,因为表达式sizeof(*spaceShipArray)等价于表达式sizeof(struct spaceShip)

那就是取消引用指针spaceShipArray会给出一个类型的对象struct spaceShip。指针不知道它们是指向单个对象还是数组的第一个元素。

如果你想输出分配内存的大小,那么你应该写例如

printf("size of spaceShipArray = %zu bytes\n", amount * sizeof(*spaceShipArray));

这个说法

printf("size of name char array = %zu \n", sizeof(spaceShipArray[0].name));

输出类型指针的大小,char *因为它是表达式的类型spaceShipArray[0].name

所以程序输出是正确的。

考虑到您忘记释放为字符数组分配的内存。例如

free( spaceShipArray[0].name );
free(spaceShipArray);

推荐阅读