对于字符指针和阵列堆栈指针的区别 [英] Stack pointer difference for char pointer and array

查看:117
本文介绍了对于字符指针和阵列堆栈指针的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符排列如下:

 char buffer[100]

和另一个字符指针如下:

 char *buffer
 buffer = malloc(100)

当我使用 GDB 检查出栈指针,它们实际上是不同的。为什么呢?

When I use GDB to check out the stack pointer, they are actually different. Why?

推荐答案

这是因为字符缓冲区[100] 将在栈上分配,这将占据100字节的存储空间。因此堆栈指针尤其 / RSP 将指向更低的内存(以堆栈向下增长)

That is because the char buffer[100] will be allocated on the stack, which will occupy 100 bytes of storage. Therefore the stack pointer esp/rsp will point to a lower memory (taking stack grows downwards)

 +-    +------------+   <-- ebp
 |     |            |
 b     +------------+
 u     |            |
 f     +------------+
 f     |            |       holds 100 elements of buffer array       
 e     +------------+
 r          .
            .
 a          .
 r     +------------+
 r     |            |
 +-    +------------+  <-- esp

而在的char *缓冲区只有一个的char * 键入对象的内存(的sizeof(字符*))将在堆栈上分配。当你做 =缓冲区的malloc(100)有保证的100字节的内存块的基地址将被退回。这个分配的存储器通常是从堆中取出。因此现在缓存持有刚刚分配的内存块的基址。因此,在这种情况下,因为内存是从堆和栈只持有的char * 键入对象,因此堆栈指针较高位置(以堆栈向下生长)

And in the case of char *buffer only one char * type object's memory (sizeof (char *)) will be allocated on the stack. When you do buffer = malloc (100) the base address of a memory block with 100 bytes guaranteed will be returned. This allocated memory is generally taken from the heap. Therefore now buffer holds the base address of the just allocated memory block. So, in this case because the memory is from the heap, and the stack only holds the char * type object, therefore the stack pointer is on higher location (taking stack grown downwards)

    +------------+   <-- ebp
    |   0xabcd   |             buffer , char * type
    +-----+------+   <-- esp
          | 
          |
          |             0xabcd 0xabce
          |             +-----+-----+-----+       +-----+-----+
          +------------>|     |     |     | . . . |     |     | 
                        +-----+-----+-----+       +-----+-----+
                                     0xabcf . . .

                        |                                     |
                        +------ 100 bytes mem block in heap --+ 

另外请注意理查德·罗斯三世的评论。

Also note Richard J. Ross III's comment.

这篇关于对于字符指针和阵列堆栈指针的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆