我对正在发生的事情感到非常困惑。我一直认为 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/