Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
392 views
in Technique[技术] by (71.8m points)

c - Stack pointer difference for char pointer and array

I have a char array as below:

 char buffer[100]

And another char pointer as below:

 char *buffer
 buffer = malloc(100)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...