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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
That is because the
char buffer[100]will be allocated on the stack, which will occupy 100 bytes of storage. Therefore the stack pointeresp/rspwill point to a lower memory (taking stack grows downwards)And in the case of
char *bufferonly onechar *type object’s memory (sizeof (char *)) will be allocated on the stack. When you dobuffer = 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 nowbufferholds 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 thechar *type object, therefore the stack pointer is on higher location (taking stack grown downwards)Also note Richard J. Ross III’s comment.