Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the assigned stack frame size is different for malloc() and normal array declaration?

I have two very simple recursive C programs. I was checking the stack frame size assigned by the system to each recursive frame. But I came across something I did not understand.

  • When I create a local array with size 5 in the recursive function, then the system assigns 48 bytes to each frame.

  • When I create a pointer and assign the same amount of memory with size*sizeof(), then the system assigns 32 bytes to each frame.

The way I check is, I compile my C code into assembly and see the bytes allocated. My guess for the difference is that malloc assigns from heap and normal array declaration assigns from the stack. So I am thinking these two memory parts might have different procedures?

I was expecting the memory allocated to be the same but they are different.

I call them from the main function.

void RecursiveFunction( int n )
{
    int *point;
    point = (int *)malloc(sizeof(int)*5);

    if ( n > 1)
        RecursiveFunction( --n );
    return;
}

and

#include <stdio.h>
#include <stdlib.h>

void RecursiveFunction( int n )
{
    int arr[5];

    if ( recursion_times > 1)
        RecursiveFunction( --n );

    return;
}

1 Answers

Just for completeness:

malloc allocates space from the heap, whereas local variables are allocated on the stack. Assuming an int is 4 bytes, your array takes up 4*5=20 bytes. When you allocate the array using malloc, the actual array isn't part of the stack frame, but the pointer where you restore the address returned by malloc is, which explains why the difference in stack frame size is 20-4=16.

like image 134
Scott Hunter Avatar answered Jan 30 '26 08:01

Scott Hunter