Memory allocation for recursive functions

How is memory allocated when calling recursive functions? The function has its own dedicated memory. When it is called, parameters (not related to the transfer) and variables get memory. So, when the function is again called from within the body, how is the memory allocated for the variables and parameters of the second call?

+4
source share
11 answers

A recursive function is no different from any other function - automatic local variables are allocated as a single block, advancing the stack pointer far enough to take into account the sum of their sizes (plus any addition necessary for alignment).

, , . , , .

+9

, . , , - .

+1

, . ( ) . (.. ), , .

youtube : https://www.youtube.com/watch?v=k0bb7UYy0pY

+1

( if func1) ( func2), , func2, . ( func2 func1).

10 , 10 , .

+1

, . , .

.

+1

. . , .

. void f() .

// Assume stack grows upwards
stack frame #3 <== the most recent call
stack frame #2
stack frame #1
+1

. ( "" - ), , ( ) , . , , (calee).

, . - , .

+1

Recurtion

void rev(Node* head){
if(head==NULL) return;
head=head->next;
rev(head);
cout<<head->data<<endl;}

.

NODE1 -> NODE2->NULL NODE1 NODE2 .

:

Call to rev(NODE1)
Check if it is NULL
Point to next NODE i.e. NODE2

Call to rev(NODE2)

Check if It is NULL
Point to next NODE i.e. NULL

Call to rev(NULL)

Check if It is NULL
Pointer will be returned With head = NULL

, .

+1

( ), , , , , ( ) .

, n . () n .

+1

, .

, , :

  • .
  • .
  • .
  • .
  • .
  • Buffer.
  • Callee.
+1

Source: https://habr.com/ru/post/1537327/


All Articles