Vipasana Vipasana - 5 months ago 15
C Question

Memory allocation amount to stack and heap (c)

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:

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!

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.