3

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?

3
  • I see at least two different ways in which char buffer[100] can be instantiated. Is char buffer[100] within the block of char *buffer or is it global? Are you asking the question why char buffer[100] appears on the stack and buffer = malloc(100) does not? malloc does not get its memory from the stack. Commented Oct 6, 2012 at 13:35
  • 4
    There's no such thing as a stack or a heap in C. It's a common implementation, but it's not required by the standard. Commented Oct 6, 2012 at 13:43
  • This question is going to keep coming up. We should keep this question open and close the others as dups, because this has an excellent answer (pretty pictures). Commented Apr 27, 2013 at 12:46

1 Answer 1

14

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.