这两种内存分配有什么区别?

What's the difference between these two memory allocations?

char str[10]char *str = (char *) malloc(10) 有什么区别?据我了解,他们不是都为 chars 的数组分配 10 个字节吗?

char str[10] 在堆栈上分配内存。 char *str = (char *) malloc(10) 在堆上分配内存。 Stack 和 Heap 存储在计算机的 RAM 中。 More information about stack and heap.

  1. char str[10];

全局(静态)范围 - 在 .data.bss 段中分配(取决于初始化。程序终止前无法释放。

本地(自动)范围 - 通常(大多数实现,但 C 标准不违背 "stack" 之类的任何东西)分配在堆栈上。当程序离开作用域时自动释放。

2.

char *str = malloc(10);

分配在堆上。需要使用free函数

由程序释放