Function stack during recursive calls - stack

Here is the function:
fun(int n)
{
if(n>0)
{
fun(n-1)+fun(n-2);
//does both functions have same stack//
}
else
{
return 0;
}
}
I need to know how stacks are created for this function when called repeatedly.

AFAIK,
Its not about how many stack does processor maintains, its more about how it maintains such stack.
Here, let us understand it with an example for which n=3. first fun(3) is called, which will call fun(2), which will call fun(1) and so on (as calling for fun(n-1)). So, the stack entry will be fun(3)->fun(2)->fun(1)->fun(0). As the argument is zero function will return "0". So, fun(0) is poped out from the stack. further the remaining call that is fun(n-2) is performed for n=1, for which function is returning no value. so, the execution will be done until end of function. Then similarly, fun(1) will be poped from the stack. so at this point stack has following value fun(3)->fun(2). after returning to fun(2), the next call of fun(2) (that is fun(n-2)) is called. and is added to the stack. now, stack value will be fun(3)->fun(2)->fun(0). and the same way whole code is executed. Thus it maintains the same stack for such call.
Hopefully, Helpfull.

Related

Multiple Completion blocks

I was following this tutorial:
https://medium.com/swift2go/building-grpc-client-ios-swift-note-taking-app-6133c7d74644
But I dont understand this piece of code as it got multiple completion handlers and I dont understand how this code works (I know this is part of a singleton class but what this code is doing and what is "notes?.notes" ???:
func listNotes(completion: #escaping([Note]?, CallResult?) -> Void) {
_ = try? client.list(Empty(), completion: { (notes, result) in
DispatchQueue.main.async {
completion(notes?.notes, result)
}
})
}
Im stuck at this point from 8 days straight so please help me :(
listNotes(_:) has its own completion block named completion.
In the body of the listNotes(_:)'s completion, listNotes(_:) calls an asynchronous, throwing function on the client variable named list(_:, _:).
The function list(_:, _:) has its own completion block and passes two variables into it; notes and result.
When list(_:, _:)'s completion block executes, the first thing that happens is it creates a GCD block to execute listNotes(_:)'s completion on the main thread.
Then it passes two block variables from list(_:, _:)'s closure forward into listNotes(_:)'s closure; a property on the optional variable notes also named notes (should be refactored imo) and result.
One very important thing to note here is that because client.list(_:, _:) is a throwing function and the error is never caught, if that function does throw, listNotes(_:) will never execute its completion block. I generally consider this to be very bad practice since someone could depend on that function to execute its closure regardless of success. You're essentially setting yourself up to break a promise you made in the function signature.

What does it mean to call an escaping closure after the function returns? [duplicate]

This question already has answers here:
Escaping Closures in Swift
(8 answers)
Closed 5 years ago.
I was reading the apple developer documentation's definition of escaping closures. It says "a closure is said to escape a function when the closure is passed as an argument to the function, but is called after the function returns"
I am not sure what the last part is supposed to mean, what does it mean by "after the function returns"? Does it mean "after the function returns a value"?
Take for example a call to an API. This call is going to take time, but we are going to want to do something after the call is completed. For example, say we want to refresh a UITableView with the new data that we pull. If we were to do it immediately, the data wouldn't have been received yet:
ApiObject.getObjects(completion: { (error, objects) in })
tableView.reloadData()
If we were to reload the data here, the table view will refresh immediately (before we actually have received the data). By doing it in the completion block, we are saying, run the code when we have completed the function, not when the function actually returns:
ApiObject.getObjects(completion: {(error, objects) in
self.tableView.reloadData()
})
Here we are running it once the objects have been fetched, not once the function itself has reached the end.
Edit
Maybe this will make it easier; I have the following code:
let comeInAnimation = POPBasicAnimation(propertyNamed: kPOPLayoutConstraintConstant)!
comeInAnimation.toValue = 0
comeInAnimation.completionBlock = { (anim, success) -> Void in
self.loginButton.enabled = true
self.signupButton.enabled = true
}
signUpContainingViewLeftConstraint.pop_add(comeInAnimation, forKey: AnimationString.EnterExit.identifier)
This is using the POP animation framework. In this case, I have a login and signup button, but I also have an animation for them to appear. I dont want the buttons to be clicked while they are appearing so i have their enabled set to false originally. Now you can see they get set to enabled in the completionBlock. This means, when the animation is completed, the completion block gets called and I know now is the time to set them to be enabled. Had I done it like so:
let comeInAnimation = POPBasicAnimation(propertyNamed: kPOPLayoutConstraintConstant)!
comeInAnimation.toValue = 0
signUpContainingViewLeftConstraint.pop_add(comeInAnimation, forKey: AnimationString.EnterExit.identifier)
self.loginButton.enabled = true
self.signupButton.enabled = true
Even though the enabled properties are set after the animation is called, the properties are actually being set before the animation is complete. Because the program runs line by line, the animation gets added and then immediately the properties are set (this is too early).
Note: This is an issue because these functions run asynchronously. That is, it allows the program to keep running while it is doing its thing. If this line of code blocked (stopped the program until it was compete) then putting the code in a completion block and putting it immediately after would be the same thing. In real life though, we dont want to block because it gives the appearance that the program has frozen.

Can I call a block inside a block, with both blocks being inside a method in iOS?

In my iOS project i call a method that contains 2 blocks say A & B.
Both blocks perform 2 different network calls, A goes first and based on some network response, executes block B. I've done so for tidiness since both do a lot of stuff & I've seen this work in my project but I'm not sure if it is correct to do so. Some illustration:
// somewhere in code
...
[self methodThatContainsTwoBlocks];
...
- (void)methodThatContainsTwoBlocks {
Block B ^(responseFromSingletonOperation) {
// do another network operation
[MyNetworkManagerSingleton performAnotherOperationAsynchronouslyWithCompletion:^{
// call some method when done
[self wereDone];
}
}
[MyNetworkManagerSingleton performAnOperationAsynchronouslyWithCompletion:^{
// do a network operation
// call block B with response
B(responseFromNetworkOperation);
}
}
The phrasing of my question may not be correct since the networking singleton instance takes a completion block, hence my saying, two blocks. I hope the illustration makes my question clearer though as I've only just started iOS programming and still dabbling my way with blocks since senior devs recommend them a lot.
Thanks.

Passing Data through the Stack

I wanted to see if you could pass struct through the stack and I manage to get a local var from a void function in another void function.
Do you guys thinks there is any use to that and is there any chance you can get corrupted data between the two function call ?
Here's the Code in C (I know it's dirty)
#include <stdio.h>
typedef struct pouet
{
int a,b,c;
char d;
char * e;
}Pouet;
void test1()
{
Pouet p1;
p1.a = 1;
p1.b = 2;
p1.c = 3;
p1.d = 'a';
p1.e = "1234567890";
printf("Declared struct : %d %d %d %c \'%s\'\n", p1.a, p1.b, p1.c, p1.d, p1.e);
}
void test2()
{
Pouet p2;
printf("Element of struct undeclared : %d %d %d %c \'%s\'\n", p2.a, p2.b, p2.c, p2.d, p2.e);
p2.a++;
}
int main()
{
test1();
test2();
test2();
return 0;
}
Output is :
Declared struct : 1 2 3 a '1234567890'
Element of struct undeclared : 1 2 3 a '1234567890'
Element of struct undeclared : 2 2 3 a '1234567890'
Contrary to the opinion of the majority, I think it can work out in most of the cases (not that you should rely on it, though).
Let's check it out. First you call test1, and it gets a new stack frame: the stack pointer which signifies the top of the stack goes up. On that stack frame, besides other things, memory for your struct (exactly the size of sizeof(struct pouet)) is reserved and then initialized. What happens when test1 returns? Does its stack frame, along with your memory, get destroyed?
Quite the opposite. It stays on the stack. However, the stack pointer drops below it, back into the calling function. You see, this is quite a simple operation, it's just a matter of changing the stack pointer's value. I doubt there is any technology that clears a stack frame when it is disposed. It's just too costy a thing to do!
What happens then? Well, you call test2. All it stores on the stack is just another instance of struct pouet, which means that its stack frame will most probably be exactly the same size as that of test1. This also means that test2 will reserve the memory that previously contained your initialized struct pouet for its own variable Pouet p2, since both variables should most probably have the same positions relative to the beginning of the stack frame. Which in turn means that it will be initialized to the same value.
However, this setup is not something to be relied upon. Even with concerns about non-standartized behaviour aside, it's bound to be broken by something as simple as a call to a different function between the calls to test1 and test2, or test1 and test2 having stack frames of different sizes.
Also, you should take compiler optimizations into account, which could break things too. However, the more similar your functions are, the less chances there are that they will receive different optimization treatment.
Of course there's a chance you can get corrupted data; you're using undefined behavior.
What you have is undefined behavior.
printf("Element of struct undeclared : %d %d %d %c \'%s\'\n", p2.a, p2.b, p2.c, p2.d, p2.e);
The scope of the variable p2 is local to function test2() and as soon as you exit the function the variable is no more valid.
You are accessing uninitialized variables which will lead to undefined behavior.
The output what you see is not guaranteed at all times and on all platforms. So you need to get rid of the undefined behavior in your code.
The data may or may not appear in test2. It depends on exactly how the program was compiled. It's more likely to work in a toy example like yours than in a real program, and it's more likely to work if you turn off compiler optimizations.
The language definition says that the local variable ceases to exist at the end of the function. Attempting to read the address where you think it was stored may or may produce a result; it could even crash the program, or make it execute some completely unexpected code. It's undefined behavior.
For example, the compiler might decide to put a variable in registers in one function but not in the other, breaking the alignment of variables on the stack. It can even do that with a big struct, splitting it into several registers and some stack — as long as you don't take the address of the struct it doesn't need to exist as an addressable chunk of memory. The compiler might write a stack canary on top of one of the variables. These are just possibilities at the top of my head.
C lets you see a lot behind the scenes. A lot of what you see behind the scenes can completely change from one production compilation or run to the next.
Understanding what's going on here is useful as a debugging skill, to understand where values that you see in a debugger might be coming from. As a programming technique, this is useless since you aren't making the computer accomplish any particular result.
Just because this works for one compiler doesn't mean that it will for all. How uninitialized variables are handled is undefined and one computer could very well init pointers to null etc without breaking any rules.
So don't do this or rely on it. I have actually seen code that depended on functionality in mysql that was a bug. When that was fixed in later versions the program stopped working. My thoughts about the designer of that system I'll keep to myself.
In short, never rely on functionality that is not defined. If you knowingly use it for a specific function and you are prepared that an update to the compiler etc can break it and you keep an eye out for this at all times it might be something you could explain and live with. But most of the time this is far from a good idea.

Does compiler saves argument of a function?

I have a function which is loading image by index in another thread using GCD .
So lets assume this :
-(void)loadMainImageToIndex:(long)index
{
NSDictionary *dic=[mainData objectAtIndex:index];
NSString *userImageUrl=[dic objectForKey:#"url"];
NSURL *userUrl=[NSURL URLWithString:userImageUrl];
[self downloadImageWithURL:userUrl completionBlock:^(BOOL succeeded, NSData *tdata)
{
if (succeeded)
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^
{
//do something here
dispatch_async(dispatch_get_main_queue(), ^
{
//do something here that uses the index argument
And i call this function 3 times :
[self loadMainImageToIndex:0];
[self loadMainImageToIndex:1];
[self loadMainImageToIndex:2];
Question is, when the first call will end the thread operation , and will got to the point :
dispatch_async(dispatch_get_main_queue()
Will he see in there index=0 , or will he see the last index was called (==2) ?
Question is, does he copy the whole function so when he finishes he can remember the argument that started the method ?
Another thing, does calling it 3 times at the same time, is a bad practice ?
Thanks.
Short version: there's no problem here. You're doing fine and it'll behave like you would expect (each block will have the correct value).
Longer version:
-(void)loadMainImageToIndex:(long)index
Every call to this method will push a fresh copy of index onto the stack. It will be popped (destroyed) when the method returns. Even if this method is called many times in parallel (on different threads), each will have its own copy of index on its own stack. Local variables and arguments are private to a each call of a method or function.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^
The creation of a block here "captures" (copies) all the variables that it discovers within the block. That includes index because it's used by:
dispatch_async(dispatch_get_main_queue(), ^
So, there's no problem here. Your block that is sent to the main queue will have its own copy of index, which it made at the time the block was created. The enclosing block also made a copy of index at the time it was created, and the method made a copy of the value that was passed to it as index.
Note that "when a block is created" is the point at which the ^{} is evaluated, not the point that dispatch_ functions are called. Those functions accept a block, they don't create the block. It is completely legal (and common) to create a block and store it in a variable and later pass that block to something else. The block will capture (copy) its variables at the point that it's created. This concept is called a closure.

Resources