3

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;
}
trincot
  • 317,000
  • 35
  • 244
  • 286
  • Possible duplicate of [c++: local array definition versus a malloc call](https://stackoverflow.com/q/3269627/11683) – GSerg Sep 29 '19 at 09:28
  • Assuming the "zero" frame size of 28 bytes, in the first case you have `28 + sizeof(int*)`, which on your system is 32, and in the second it is `28 + sizeof(int) * 5`, which is 48. – GSerg Sep 29 '19 at 09:29
  • But we assign extra memory with (int *)malloc(sizeof(int)*5). Does that not take up space? –  Sep 29 '19 at 11:59
  • 2
    `sizeof(int)*5` bytes is allocated from the heap. On the stack there is only a pointer to that (`int*`). – GSerg Sep 29 '19 at 12:13
  • Thank you so much, that solves my problem –  Sep 29 '19 at 13:05

1 Answers1

1

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.

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101