What's the maximum depth of recursion? [closed] - c++

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
i wonder what's the maximum depth of a recursion function. I know it has relationship with the stack size. But what's the relationship? If i write a function in 32-bit machine which dose nothing but call itself, What's the maximum depth?
unsigned long times=0;
void fun()
{
++times;
fun();
}
Then what's value of 'times' when the stack overflow?

The relationship is roughly this:
Maximum recursion depth = ((Stack size) - (Total size of stack frames in call chain up to the recursive function)) / (Stack frame size of recursive function)
The stack frame is the data that gets pushed onto the stack each time you make a function call. It consists of the function return address, space for parameters (that weren't passed in registers) and space for the local variables. It will differ for different functions but it will be constant for a given function recursively calling itself at each call.
It follows from this that a recursive function with a large number of parameters and/or large number of local variables will have a larger stack frame size, and therefore a smaller maximum recursion depth for a stack of a given size.
If the compiler performs tail recursion optimization, then the stack frame size is effectively zero after the top-level call, so the formula gives a divide by zero: no max recursion depth.
Everything I've said here probably has multiple exceptions to the rule, but this is the basic relationship.

Related

Which is better, to define the variable inside the loop or outside, with huge loop times [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
I need to use an array in a loop, and the loop time is very huge.
Case 1: define the array outside the for-loop and pass it to fun2
void fun1(){
int temp[16];
for(int i = 0;i <times; i++)
{
fun2(temp);
}
}
void fun2(int[]& temp){
/** do something with temp*/
}
Case 2: define the array in fun2:
void fun1() {
for (int i = 0; i < times; i++)
{
fun2();
}
}
void fun2() {
int temp[16];
/** do something with temp */
}
fun1 will be called very often. In this situation, which is better?
Does Case 2 have some influence on performance?
If you look for an answer to the general case, the answer is, "it depends." If you want an answer to your specific example, the answer is that the second version will be more efficient.
Ask yourself:
Is there a cost to construction / destruction / reuse?
In your example, there is none (except adjusting the stack pointer, which is extremely cheap). But if it was an array of objects, or if you had to initialize the array to a specific value, that changes.
How does the cost of parameterization factor in?
This is very minor but in your first case, you pass a pointer to the function. If the function is not inlined, this means that the array can only be accessed through that pointer. This takes up one register which could be used otherwise. In the second example, the array can be accessed through the stack pointer, which is basically free.
It also affects alias and escape analysis negatively which can lead to less efficient code. Basically, the compiler has to write values to memory instead of keeping them in registers if it cannot prove that a following memory read may not refer to the same value.
Which version is more robust?
The second version ensures that the array is always properly sized. On the other hand, if you pass an object whose constructor may throw an exception, constructing outside the function may allow you to throw the exception at a more convenient location. This could be significant for exception safety guarantees.
Is there a benefit in deallocating early?
Yes, allocation and deallocation are costly, but early destruction may allow some reuse. I've had cases where deallocating objects early allowed reuse of the memory in other parts of the code which improved use of the CPU cache.
depends on what you want to achieve..in this case, i'm assuming you are looking for performance which case 2 would be the better option as the function would create the variable on the fly instead of trying to get the variable globally then its value.

Which data structure can i use if i want to reduce its memory by half during the execution [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I want to half the number of elements that the data-structure contains. And I have to do that multiple times.
The problem is similar to this:
I have 'n' sorted integers and I have to add consecutive two numbers. Thus the number of the number of integers I am left with is n/2.And I have to loop this till I get a single number. ( I simplified the problem, I have to do other operations side by side)
I thought trying an array of size n, then thought I will create an array of size n/2 and will fill this new array, and finally will free the original array(was created using a pointer). Note that I also have to store the data I evaluated each time through the loop.
If I am not able to explain, please refer to this problem
MIXTURE
Use a pointer to memory allocated with malloc (or calloc, or similar), then resize it with realloc:
int main()
{
int* myArray = malloc(50 * sizeof(int)); // gets you 50 integers
// perform operations on myArray, accessing it like myArray[3]
int* r = realloc(myArray, 25 * sizeof(int));
if (r) {
myArray = r;
}
// perform some more operations.
free(myArray); // free the memory once you are done with it
}
realloc returns a new pointer that points to memory of the same content as the pointer you passed before. Assign the result back to myArray like this to get the desired behavior, and when you don't need the array anymore, call free on it just like you would do normally if you haven't reallocated it.
Which data structure can i use if i want to reduce its memory by half during the execution
I want to half the number of elements that the data-structure contains. And I have to do that multiple times.
You can use any dynamically sized data structure, which is pretty much all data structures except the statically sized array.
Although, note that reducing the size of memory allocated for std::vector (upon calling shrink_to_fit) is technically not guaranteed to happen. Example using vector:
vec.resize(vec.size() / 2);
vec.shrink_to_fit();

Is it possible to report stack usage for each module during compile C++ code? [duplicate]

This question already has answers here:
How to determine maximum stack usage in embedded system with gcc?
(7 answers)
Closed 7 years ago.
I am doing mixed language simulation with modelsim, part of the code is written in SystemC (C++), then I got stack overflow when I use the SystemC code. I am not sure how to trace this issue. Just want to check if it is possible to report the stack usage during compile the C++ code?
the compiler can't tell exactly how much the max stack size will be since it depends of many things. if you have a recursion, the compiler can't foretell what will be the inputs, if you have threads there will be more then a single stack, and so on.
how to trace?
for each code block, this is the stack frame: from the address of the first variable in the current function, note that the first variable may be a by value argument(not by reference), first or last, depending the calling convention, to the last declared variable in the current block, plus the sizeof the last variable. before the frame there is the return value(type size) and the return address (pointer size), so you can tell how many bytes each function takes on the stack, the current frame can be compared to the first main (or thread entry) variable address to alert you when you getting close to the limit. note that thread stack usually have different stack size than the main thread.
In non-recursive functions, yes: just add up the sizes of the parameters and local variables and add a couple or words for the return address and base pointer.
In recursive functions it isn't possible in general, although if the recursion is based on conditions that can be evaluated at compile time it might be feasible in limited cases.
I'm not aware of any compilers that do any of this.

How to get the number of elements [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm developing an application in C++ and I need to know the number of elements of a variable. I'm looking for how to do this but I'm not able to find a solution for this. The variable is defined in this way:
unsigned char *values = (unsigned char *) some_function(some_parameter);
// "some_function" takes "some_parameter" and fills "values" correctly
Thanks in advance for any help you can provide.
Best regards.
Since you told us which function you're using (FreeImage::GetBits), we now know that you're querying the raw data of an image. Its size is the product of the pitch and height of the image, as seen in this formula:
int size = image.GetPitch() * image.GetHeight();
This is the size in bytes, which is the number of elements if you access a char pointer. But speaking of "number of elements" in such a case (where we speak of some low-level memory, a bit stream with no high-level types) is a bit misleading, as when reading the question one might think it's about a higher level array.
In case you wonder: Raw image data is typically laid out in rows of size pitch, one pixel after another, from left to right, where the size per pixel can depend on some storage format (for example 1 byte grayscale, 3 bytes RGB with 8 bit per channel, 1 bit for monochrome bitmaps, and many more formats).
These rows are laid out from top to bottom (in most cases) or sometimes from bottom to top (in the case of BMP file format for example). The pitch is at least the width of the image times the size per pixel, so all pixels have space in such a "scan line", which is how such a memory per line of the image is called. It's rounded up to some alignment, so every line can start at an aligned address in the memory for the whole image. The unused space is called "padding" and ignored.
Depending on the library, sometimes "pitch" means "pixels per line" in the memory, not "bytes per line", but in this case it's already given in bytes so you only have to multiply by the image height. Note that typically the height is not padded like the width, since there's no advantage of doing so.
You can never deterministically know the length of an array given a pointer to the beginning of the array. You must pass some information along with the array.
That extra information may be in the form of:
another return value specifying the length
an agreed encoding that encodes the length into the beginning of the array
an agreed encoding that marks the end of the array (e.g. \0 at the end of a string)

how are the memory cells organized on a RAM and how is it related to C++? [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this question
As far as I can understand, RAM is organized like a net of rows and columns of cells, each cell containing 1 byte. Also, each cell is label with an address memory written in hexadecimal system. Is this so? Now, when running a c++ program, I suppose it uses the RAM as a mean of storage. In this case, as the char type on c++ is the basic unit of storage, is this size of a char exactly the same as the cell (1 byte)?, does the size of a char depends on the size of a cell (in case the size of a cell is not 1 byte)?, does it depend on the compiler? Thank you so much.
It is easy to visualize RAM as a net of rows and columns. This is how most CS classes teach students as well and for most purposes this would do well at a conceptual level.
One thing you must know while writing C++ programs is the concept of 2 different memories: stack and heap. Stack is memory that stores variables when they come in scope. When they go out of scope, they are removed. Think of this as a stack implementation (FIFO).
Now, heap memory is slightly more complicated. This does not have anything to do with scope of the variable. You can set a fixed memory location to contain a particular value and it will stay there until you free it up. You can set the heap memory by using the 'new' keyword.
For instance: int* abc = new int(2);
This means that the pointer abc points to a heap location with the value '2'. You must explicitly free the memory using the delete keyword once you are done with this memory. Failure to do so would cause memory leaks.
In C, the type of a character constant like a is actually an int, with size of 4. In C++, the type is char, with size of 1. The size is NOT dependent on compiler. The size of int, float and the like are dependent on the configuration of your system (16/32/64-bit). Use the statement:
int a=5;
cout<<sizeof(a)<<endl;
to determine the size of int in your system.