3

I try to understand something about the amount of memory allocated to the stack and to the heap. Suppose sizeof(char) = 1 byte, and sizeof(void *) = 4 byte. given the following code:

#include<stdio.h> #include<stdlib.h> #include<string.h> int main() { int i; char *str1 = "hello"; char str2[] = "hello"; char *str3 = (char*)malloc(strlen(str2)); //free code return 0; } 

We have been told that the amount of memory allocated to the heap is 5 bytes, and I understand that indeed this is the amount in the malloc (strlen(str2) = 5). But, what I don't understand is how the amount of memory allocated to the stack is 18 bytes? I thought that if they give us the information that a pointer size is 4 bytes, so we have 4 bytes for the pointer str1 and another 6 bytes for the array str2 (including the '/0'). What am I missing? where are the 18 bytes for the stack comes from? Thanks in advance for your help!

1
  • What about i and str3? Commented Aug 27, 2016 at 15:17

1 Answer 1

3
int i; // 4 stack bytes char *str1 = "hello"; // 4 stack bytes (pointing to a read only string constant) char str2[] = "hello"; // 6 stack bytes (containing a 6 byte string) char *str3 = (char*)malloc(strlen(str2)); // 4 stack bytes (pointing to heap memory from malloc) 

Total: 18 stack bytes

This is an idealistic calculation, the reality might be more complicated. It is still useful as a model for understanding memory.

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

2 Comments

@Vipasane: I extended the comments to address your remaining question
Thanks a lot for your effort! You really helped me.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.