c - 为什么 char[] 在堆栈上,而 char * 在堆上?

标签 c pointers memory

我对正在发生的事情感到非常困惑。我一直认为 char *char [] 是可以互换的,但是在查看内存地址之后,似乎 char * 在堆中分配空间,而 char [] 在堆栈上分配内存。

char stack[] = "hello";
char *heap = "hello";

char *heap_string_malloc = malloc(5);
heap_string_malloc = "hello";

printf("Address of stack[0]: %p\n", stack);
printf("Address of heap[0]: %p\n", heap);
printf("Address of heap_string_malloc[0]: %p\n", heap_string_malloc);

输出以下内容:

Address of stack[0]: 0x7fff8b0b85b0
Address of heap[0]: 0x400760
Address of heap_string_malloc[0]: 0x400760

这是否意味着 char * 是动态分配的?

更令我困惑的是,malloc 为何分配的内存地址与 char *heap 已分配的内存地址相同?我没有进行任何优化(只是 gcc file.c)。

最佳答案

Arrays are not pointers .您的程序正在逐行执行的是

// Allocate 6 bytes in the stack and store "hello" in them
char stack[] = "hello";

// Allocate pointer on the stack and point it to a static, read-only buffer
// containing "hello"
char *heap = "hello";

// Malloc 5 bytes (which isn't enough to hold "hello" due to the NUL byte)
char *heap_string_malloc = malloc(5);

// Reset heap_string_malloc to point to a static buffer; memory leak!
heap_string_malloc = "hello";

您看到同一个指针两次的原因是编译器优化掉了第二个包含 "hello" 的静态缓冲区。

关于c - 为什么 char[] 在堆栈上,而 char * 在堆上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19656025/

相关文章:

java - FloatBuffer 损坏问题

c - 适合中等简单 TCP 服务器的良好架构

c - 链表的二维数组

c - 对指向结构数组的指针执行算术运算时出错

c# - char* 到 C# 中的字符串

c - 函数 "main"的代码在目标文件中的哪里开始?

c - 为什么c中出现 '%' conversions than data arguments错误时输出随机整数?

c - 符号链接(symbolic link)奇怪的问题

c++ - 从 QString* 到 QString& 的转换

c++ - 从 SDL 库的函数返回的指针