c# memory allocation in Stack/Heap occurs [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 6 years ago.
Improve this question
In c# When does the memory allocation in Stack/Heap occurs. Is it during the runtime or compile time. From my study I understand that all memory allocations happens during run time for both value type and reference type. Is this correct?

How would it happen during compile-time ? The program is not yet running and there is no need to allocate memory before the program run. It is common sense that this should happen at run-time (When actually executing the generated IL).
Memory management it also optimized that it may not happen when you just create the variable, but when you first use it.

I think you might be confusing the actual allocation, which can only happen at runtime when the program is actually running, with the allocation calculation/determination. For example, consider the following method:
void Foo()
{
int i = 42;
Console.WriteLine(i);
}
The compiler will now statically (compile-time) that i will require 4 bytes of space on the stack. However, it will not be until the program actually runs that the actual allocation takes place.
Moreover, the above method won't even be compiled into machine code (a prerequisite for any operation such as allocation) until the CLR loads the code and passes it to the JIT (Just in Time compiler). Of course, even if it did, it's not until the actual process is created that the OS even allocates a memory address space for it to use...

Related

Why are Arrays reference types? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
int[] age=new int[5];
After reading many posts and blogs ,I am still not clear about the fact why arrays are reference types.I know this question is like very old and have been asked plenty times but still couldnt find direct answer.
Known things :Since Arrays are allocated on heap,hence they are reference types .
Need to know:Whats the reason behind making(compiler) arrays as reference types?.
Suppose age[0]=5,age[1]=25 ,what is the difficulty in assigning these on stack or make reference to heap if their type was object.why consider heap as accessing time is slow comparatively?.
Why heap ,why not on stack like for structures?.
Several reasons:
value types are passed by value (as in copied). So if you called a method with a value-type array, you'd be copying all the contents.
Stack memory is limited and primarily designed for quick access to parameters that are in current use (as implied by the term stack). Putting a large object onto the stack would cause lookups of other local state to take much longer, because they wouldn't all be on the same cache line in the CPU cache anymore.
Array contents are modifiable. So you'd have all the issues that you have with mutable structs when you tried to set a value, only to find that the copy, not the "original" was modified.
EDIT:
Yes you can use stackalloc in unsafe code. Doesn't make it a good idea.

How to prevent MSIL runtime injection? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
As seen here Programmatic MSIL injection or here http://www.codeproject.com/Articles/463508/NET-CLR-Injection-Modify-IL-Code-during-Run-time you can modify IL code at runtime using some tricky injections.
My question is : how to prevent that? For instance, if someone use that to bypass a security feature, how can i avoid that security hole?
how to prevent that?
You can't, as far as I understand. But you can do make it not easy.
In the simple case, you don't even need to inject IL. You can do IL weaving to modify the assembly. For example, you can find the login method ant delete the original IL code and simply return true, or you can jump to your own login method.
public bool Login(string userName)
{
// original method did security checks
// and return true if the user is authorized
// your implementation can return true or jump to other method
}
For this you must to do it when the application is not running, you modifying the assembly itself. You can do it with mono.cecil and you can look on StaticProxy.Fody for example.
The other case is inject code to running assembly. and this is divide to two cases:
When the code isn't jitted\ngen'd
When the code is jitted\ngen'd
For the first case is more easy, You still have the IL of each method and you inject your own IL instructions.
The second case is more complex because the Jitter redirect the IL pointer to the machine code.
For two of them you can see a bunch of articles\libraris to make the inject work.
Codecope
Article 1
Article 2
But even if you however make it impossible to inject, you still not protected. Because you can modify the bytes itself. See this article for details.
For all above method, there is cases when it more complex to do the work. For example, Generics, DynamicMethods, prevent load assemblies to your process (which is needed in some cases).
To summarize, you can do it very hardly to inject your code but not prevent it.

Is it safe to access a method of C# from an unmanaged C library? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I'm accessing a method of C# from C now. Below is some snippet of code in C#.
IntPtr pFunc = Marshal.GetFunctionPointerForDelegate (
new DelegateForMyMethodInCsharp (
MyMethodInCsharp
)
);
setFuncPtr(pFunc);
setFuncPtr() is a function of a C library to set the pointer of a C# method. After this code I can call the C# method in the C library whenever I want without any problems but I'm not sure if this is okay.
When using pointers for variables stored in heap in C#, the keyword 'fixed' must be used due to GC. Because the stack section of memory contains methods, it makes sense for me to write code like above. But because I haven't seen people write that way yet, I hope to hear your opinions.
This is a very simple question, but a very important question to me.
I don't want to write unsafe code.
You need to make sure that the delegate instance is not garbage collected.
To do that, you can simply store it in a field, and make sure that field is rooted for as long as the unmanaged code hangs on to the pointer.
This is necessary because delegates store not just a pointer to a .Net method, but also state (the first argument; typically this). To make a function pointer for that, the runtime must create a thunk that refers to this object, so that unmanaged code can get there from nothing but a function pointer. This is bounded by the lifetime of the delegate instance.
For more information on the difference between delegates and function pointers, see my blog.

Clear garbage memory of other software in c# [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
this is a strange question.
In my work I use a software (that NO one can modify or take vision of source code), this software, unfortunately, is very bad. It uses, when launched, about 1 gb RAM, but running and being used, it accumulates data in ram and after few hours it occupies over 4gb of ram, and can accumulates more and more if not stopped. Since not all pc of my company can handle this, they crash. Is there a way to clear data unused in ram from other software programming in c#?
I just need an hint, i program in c#.
I'm sorry for my English, and if this question is somehow wrong.
Thanks for time.
Edit: I will add some information about this software understand better what I can do, and what I cant't.
Since i would not gain anything hacking this software, but I would have a better life (and not only me but my co-workers and employees too), i don't see any issue in hacking this software. (well, my chief has no problems, and his chief too).
I will try the Arunasr hint, I program in c# and know this function. I will only have to decompile it.
I have to delete this question?
Thanks for all replies and all help you gave to me.
There is no such way, outside of killing and restarting that task. If it is a Windows Service, you can use Powershell, command line utility SC.exe, or this c# code:
public static void RestartService(string serviceName, int timeoutMilliseconds)
{
ServiceController service = new ServiceController(serviceName);
try
{
int millisec1 = Environment.TickCount;
TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);
service.Stop();
service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
// count the rest of the timeout
int millisec2 = Environment.TickCount;
timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds - (millisec2-millisec1));
service.Start();
service.WaitForStatus(ServiceControllerStatus.Running, timeout);
}
catch
{
// ...
}
}
Reference: http://www.csharp-examples.net/restart-windows-service/
.NET runtime garbage collector tends to be lazy and only collects when free memory is about to run out. You can force garbage collection with GC.Collect(), but mind the performance: it is expensive if you do it frequently.
If the library really accumulates data (i.e. data remains references and GC cannot touch it), there is little you can do other than hack up the library, figure out what eats up the memory and release the unnecessary objects. It is not difficult to decompile the .NET bytecode. In the extreme, you can modify the assembly bytecode using reflection after it has been loaded. I would not recommend it unless you are desperate.
You can use GC to track real memory usage stats.

Initializing an instance with no use [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 8 years ago.
Improve this question
I'm a little bit confused why type instances are allowed to be created without their future use and the compiler doesn't emit even a warning about it.
public void M()
{
new int();
new object();
}
I've never created an instance without assigning it to a variable or calling it's members, and if I saw a line like ;new SomeType(); I would consider it as a mistype. I understand that technically .ctor can assign some static fields or do something else it's not supposed to do, but I don't consider it a sufficient argument for not emitting a warning.
Are there any patterns where ignoring an instance is appropriate? What am I missing?
Additional points not clear for me:
1. CodeAnalysis gives a warning "CA1806: Do not ignore method results" for object but not for int or any other value type.
2. The compiler doesn't emit IL for ignored structs even without optimization flag.
Instantiating an object can have side effects in C#.
The constructor could do almost anything, such as creating a database entry, writing a text file, or updating a static property somewhere before going out of scope.
Having said that, it is not good programming style to instantiate an object for the sole purpose of producing a side effect. That is what the CodeAnalysis warning is implying.
I understand that technically .ctor can assign some static fields or do something else it's not supposed to do, but I don't consider it a sufficient argument for not emitting a warning
As Eric Lippert said
My usual response to “why is feature X not implemented?” is that of course all features are unimplemented until someone designs, implements, tests, documents and ships the feature, and no one has yet spent the money to do so. And yes, though I have famously pointed out that even small features can have large costs, this one really is dead easy, obviously correct, easy to test, and easy to document. Cost is always a factor of course, but the costs for this one really are quite small.
http://blogs.msdn.com/b/ericlippert/archive/2009/05/18/foreach-vs-foreach.aspx

Categories