Stack of a stack c# - c#

So I have a stack of a few stacks.
This is how I implemented the stack: public Stack<Stack<Baggage>> Trunk;
So trunk is supposed to hold multiple stacks of baggage (one baggage stack has a limited number of bags it can hold)
The question I have is, how would I write out the trunk stack.
Ive tried using the pop() function but on the console it writes out this: System.Collections.Generic.Stack1[TestDummy.Baggage]` I tried making an override ToString method in the baggage class but it doesn't work.
thank you for your help!

From what I understood, you are trying to print Trunk content to console. You must keep in mind that inside your Trunk stack there are another stacks, so you should pop a value from that stack too, to get it
Here is a simple example code:
foreach(var baggage in Trunk.Pop())
{
Console.WriteLine(baggage.Name);
}
Trunk.Pop() will take off stack from Trunk and foreach loop will iterate through elements of that stack and perform some action

Related

Why does this recursive method cause a Stack Overflow error when it has no variables?

I have recursive method like this, which doesn't contain any variable. Why is it throwing a stack overflow exception?
class MainClass
{
static void Main() => Bark();
static void Bark() { Bark(); }
}
in the example above, I did not create any variables. If I create any variable(either as a parameter or inside a method), then this is understandable: many variables have been created in the thread's stack, and due to the lack of memory, I get an error.
I don't understand, is the method itself is also stored on the stack? Why am I getting the error?
The stack frame does not just contain parameters, it also contains a return address, so that the processor knows where to go back to.
Furthermore, the hidden this pointer is also a parameter. To remove that you would need a static function.
There is also the ebp or other stack-frame pointer, which can be pushed onto the stack for each call, depending on the exact calling convention.
So whatever you do, you will definitely get a stack overflow at some point, unless the compiler decides to perform tail-recursion.
If you were to debug this piece of code and look at the "call stack" window then you would see it attempt to add Bark to the call stack an infinite amount of times because the recursion has no end point.
I believe what you're expecting to see is tail recursion. Unfortunately C# compiler doesn't support it.

Can a .NET stack trace be generated that excludes internal methods?

Sometimes when an exception happens on a .NET class method, that method itself internally is calling a bunch of other methods but the error happens inside one of those. This makes for a bloated and messy stack trace with more "meaningless" stuff than needed. Is there a way to get a stack trace that stops at the public .NET method that caused the error vs having it show all the internals of the .NET methods?
An example of this would be ADO.NET's ExecuteNonQuery(). Internally that calls like 5-6 functions and the exception may not happen until that 6th nested function and so the stack trace shows all of those internals which we can't do anything about or care about. It would be nice and cleaner if it stopped at ExecuteNonQuery() since that's the public facing .NET method.
The short answer is "no", you can't change the way .NET generates stack traces. When a stack trace is generated, it shows every call site. However, if you want to have some custom behaviors, you can write some custom code to edit the output of a stack trace you generate.
To generate a stack trace, you use code like this:
StackTrace stackTrace = new StackTrace();
StackFrame[] stackFrames = stackTrace.GetFrames();
The constructor will generate the stacktrace data, and .GetFrames() will return the methods to you. From that point, you can filter them as you wish (use stackFrame.GetMethod() to get the method info for each frame -- either to filter it or to add it to a StringBuilder for your string output, etc)
Reference: https://msdn.microsoft.com/en-us/library/system.diagnostics.stacktrace(v=vs.110).aspx

Push a stack onto another stack

In C#, is there a way to push one Stack onto another Stack without iterating through the stack elements? If not, is there a better data structure I should be using? In Java you can do:
stack1.addAll(stack2)
I was hoping to find the C# analogue...
0. Safe Solution - Extension Method
public static class Util {
public static void AddAll<T>(this Stack<T> stack1, Stack<T> stack2) {
T[] arr = new T[stack2.Count];
stack2.CopyTo(arr, 0);
for (int i = arr.Length - 1; i >= 0; i--) {
stack1.Push(arr[i]);
}
}
}
Probably the best is to create an extension method. Note that I am putting the first stack "on top" of the other stack so to speak by looping from arr.Length-1 to 0. So this code:
Stack<int> x = new Stack<int>();
x.Push(1);
x.Push(2);
Stack<int> y = new Stack<int>();
y.Push(3);
y.Push(4);
x.AddAll(y);
Will result in x being: 4,3,2,1. Which is what you would expect if you push 1,2,3,4. Of course, if you were to loop through your second stack and actually pop elements and then push those to the first stack, you would end up with 1,2,4,3. Again, modify the for loop as you see fit. Or you could add another parameter to specify which behavior you would like. I don't have Java handy, so I don't know what they do.
Having said that, you could do this, but I don't make any guarantees that it will continue to work. MS could always change the default behavior of how stack works when calling ToList. But, this is shorter, and on my machine with .NET 4.5 works the same as the extension method above:
1 Line Linq solution:
y.Reverse().ToList().ForEach(item => x.Push(item));
In your question, wanting to do this "without iterating through the stack elements" basically means a LinkedList-based stack where you would just join the first and last elements to combine stacks in constant time.
However, unless you've a very specific reason for using LinkedList, it's likely a better idea to just iterate over an array-based (List-based) stack elements.
As far as a specific implementation goes, you should probably clarify whether you want the second stack to be added to the first in the same stack order or to be reversed into the first stack by being popped out.
An addAll would just be a convenience method for a foreach loop that adds all of the items. There really isn't much you can do besides that:
foreach(var item in stack2)
stack1.Push(item);
If you do it particularly frequently you can add an extension method for it, for your own convenience.
This isn't meant to be done with the current .NET Stack implementation.
In order for the content of a Stack to be "grafted" onto the end of another Stack without iterating though its elements internal implementation details how the Stack class stores them in memory has to be known. Based on the principle of encapsulation this information is "officially" only know inside the Stack class itself. .NET's Stack does not expose methods to do this, so without using reflection there is no way to do it as the OP requested.
Conceivably you could use reflection to append to the internal array of one Stack the content of another Stack and also update the field that stores the stack length but this would be highly dependent on the implementation of the Stack class which could be changed in future versions of the framework without warning.
If you really need a Stack that can do this you could write your own Stack class from scratch or simply use another collection like ArrayList or LinkedList which have the method you want and add Push and Pop extension methods to them.

C# Stack Overflow Overwrite EIP

I would like to write a vulnerable program, to better understand Stack Overflow (causes) in c#, and also for educational purposes. Basically, I "just" want a stack overflow, that overwrites the EIP, so I get control over it and can point to my own code.
My problem is: Which objects do use the stack as memory location?
For example: the Program parses a text file with recursive bytewise reading until a line break is found (yeah, I think nobody would do this, but as this is only for learning...). Currently, I'm appending a string with the hex value of chars in a text file. This string is a field of an object that is instanciated after calling main().
Using WinDbg, I got these values after the stack has overflown from (nearly) endless recursion:
(14a0.17e0): Break instruction exception - code 80000003 (first chance)
eax=00000000 ebx=00000000 ecx=0023f618 edx=778570b4 esi=fffffffe edi=00000000
eip=778b04f6 esp=0023f634 ebp=0023f660 iopl=0
BTW I'm using a Win7x86 AMD machine, if this is from interest.
I've seen many C++ examples causing a stack overflow using strcpy, is there any similar method in c#?
Best Regards,
NoMad
edit: I use this code to cause the stack overflow.
class FileTest
{
FileStream fs = new FileStream("test.txt", FileMode.Open, FileAccess.Read);
string line = String.Empty;
public FileTest()
{
Console.WriteLine(ReadTillBreak());
}
private string ReadTillBreak()
{
int b = 0;
b = fs.ReadByte();
line += (char)b;
if (b != 13)
ReadTillBreak();
return line;
}
}
Is it possible to overflow the stack and write into the eip with the line string (so, content of test.txt)?
The reason you can do exploit stack corrupts in C and C++ is because you handle memory yourself and the language allows you to do all sorts of crazy stuff. C# runs in an environment that is specifically designed to prevent a lot of these problems. I.e. while you can easily generate a stack overflow in C# there's no way that you can modify the control flow of the program that way using managed code.
The way exploits against managed environments usually work is by breaking out of the sandbox so to speak. As long as the code runs in the sandbox there are a lot of these tricks that will simply not work.
If you want to learn about stack corruption I suggest you stick to C or C++.
I'm not entirely clear on you descriptions of what you have tried. Stack overflows do not generally "overwrite the EIP".
To cause a stack overflow, the most straight forward way is something like this.
void RecursiveMethod()
{
RecursiveMethod();
}
Since each call to this method stores the return address on the stack, calling it endlessly like this without returning will eventually use up all stack space. Of course, modern Windows applications have tons of stack space so it could take a while. You could increase the amount of stack usage for each call by adding arguments or local variables within the method.

How to copy items from list to stack without using loop

I do have a Stack and a List. I need to copy all the items from list to stack without using loops i.e for, foreach.. etc.
Is there recommended way of doing it?
You can create a stack from anything that is IEnumerable
var myStack = new Stack<MyObjectType>(myList);
See MSDN: http://msdn.microsoft.com/en-us/library/76atxd68.aspx
However, the stack constructor will be using a loop internally, you just don't see it.
If you want to Pop the items in the same order as they appear in your list,
then reverse your list before you create the stack from it.
var myStack = new Stack<MyObjectType>(myList.Reverse());
new Stack<T>(myListOfT)
Alternatively (without loops)
myStack.Push(myList[0]);
myStack.Push(myList[1]);
myStack.Push(myList[2]);
myStack.Push(myList[3]);
...
It's going to get pretty tedious. What's wrong with loops?
In java 1.8 Stack has a predefined method call addAll - Item will be push on to the stack
stack.addAll(list);

Categories