how to find allocated memory by a variable? - c#

class app {
public int x = 3;
static void Main(string[] args)
{
}
}
it's possible get the memory address allocated by x variable?
the example can be in C, C++, C# or D.
I hope it is clear
Thanks in advance

The ampersand (&) is the "address-of" operator in most C-like languages:
int x;
printf("Address of x is %p\n", &x);
The return value of & is effectively a pointer to its operand.

In C and in C++ this is fairly straight-forward. I'll give the example in C++:
struct App
{
int x;
App() : x(3) { }
};
int main()
{
App a;
int * p = &a.x; // address goes here
}
There is of course no such thing as "the variable App::x", since App is only the type. Each instance of this type, such as a in the example, carries its own set of member variables, and a pointer to the member variable is readily obtained. (The same is true for plain data structs in C.)
Note that C++ has another, related feature: Member pointers. This allows us to form the opaque value int App::*pm = &App::x which by itself doesn't point to anything, but only carries information about the offset of App::x inside the class, if you will. This animal can be used together with an instance to obtain the actual value, e.g. a.*pm.

Skipping D and E. C# and F# (and other CLR languages) - there is no fixed addres for any partcular variable in general. One can use managed debugger (i.e. WinDbg + SOS) to find address of any particular variable, or use fixed along with interop classes.

Related

How to create/destroy objects in "modern" C++?

I am porting C# app into C++ linux app. I am confused with construction and destruction in "modern" (C++11 ?). I always thought you have to use new/delete but now it appears C++ recommendation is not to do so (is this correct or I read a wrong blog?).
What I have roughly (there are 6 subclasses of B and BRec atm):
class ARec : public BRec
class A : public B
. . .
class Factory
BRec GetRecord(WrapperStruct s)
{
if(s.Type == 'A')
{
A* a = (A*)s.Data;
auto rec = ARec((ushort)a->Num);
rec.OtherField = a.OtherField;
return rec;
}
. . .
main
// separate pthread
void* Logger(void* arg) {
int* thread_state = (int*)arg;
auto f = Factory();
WrapperStruct item;
while (true)
{
q->try_dequeue(item);
auto rec = f.GetRecord(item);
auto bytes = f.GetBytes(rec);
// write bytes to file ...
delete bytes;
if(*thread_state == -1)
pthread_exit(0);
}
Question - how does compiler would know when to delete s.Data in factory method? Same - rec if it was created in a class method and then crossed to other method (while in Logger)? Is there a simple guide how to manage variables' memory in C++11 ?
EDIT: s.Data contains ref to an object created in a 3rd party dll and can be of different types hence the s.Type field
Smart pointers are the key.
std::shared_ptr<Foo> foo = std::make_shared<Foo>();
std::unique_ptr<Foo> bar = std::make_unique<Foo>();
Shared pointers can be copied. They do reference counting. When the reference count drops to zero, they'll delete their contents automatically.
Unique pointers can't be copied. They can be copied by reference. When the unique pointer goes out of reference, it frees the object for you.
So it works a lot like Java now.
void notAMemoryLeak() {
std::shared_ptr<Foo> foo = std::make_shared<Foo>();
}
Other than that, you treat them like pointers. The syntax for their use at this point is identical, except you're passing smart pointers, not Foo *.
void myFunct(std::unique_ptr<Foo> &foo) {
cout << "Foo: " << foo->getName() << "\n";
}
The make_shared and make_unique can take the same arguments as any of your Foo's constructors, so feel free to pass stuff.
I do one more thing:
class Foo {
public:
typedef std::shared_ptr<Foo> Pointer;
...
};
Foo::Pointer foo = std::make_shared<Foo>();
Sometimes I also create static methods to make it even cleaner. This is stylistic and not necessary. Some people might fault me. But it's clean and easy to read.

In C#, why can't I populate a local variable using its address, then use the variable later?

Consider the following code:
private unsafe void Function()
{
int length;
// This line raises error CS1686, "Local 'length' or its members cannot have their address taken and be used inside an anonymous method or lambda expression".
glGetProgramiv(1, GL_PROGRAM_BINARY_LENGTH, &length);
FunctionWithLambda(() => Console.WriteLine(length));
}
private void FunctionWithLambda(Action callback)
{
callback();
}
Note that I'm taking the address of length (a local variable), then using the variable itself (not its address) in a lambda. I understand why a local variable address can't be used in a lambda directly (see Why cannot I pass the address of a variable to an anonymous function?, among other examples), but why can't I use the value of length once assigned (even if that assignment happens to use the & operator)? The official documentation for error CS1686 (https://learn.microsoft.com/bs-latn-ba/dotnet/csharp/misc/cs1686) hasn't clarified this confusion.
My assumption is that this is simply a language limitation, but I'm curious if there's an underlying technical reason I'm missing. Also note I'm not asking how to work around this problem (I know I can easily copy length to another local variable first).
The C# specification says the following (my bold):
23.4 Fixed and moveable variables
The address-of operator (§23.6.5) and the fixed statement (§23.7) divide variables into two categories:
Fixed variables and moveable variables.
...snip...
The & operator (§23.6.5) permits the address of a fixed variable to be obtained without restrictions. However, because a moveable variable is subject to relocation or disposal by the garbage collector, the address of a moveable variable can only be obtained using a fixed statement (§23.7), and that address remains valid only for the duration of that fixed statement.
In precise terms, a fixed variable is one of the following:
A variable resulting from a simple-name (§12.7.3) that refers to a local variable, value parameter, or parameter array, unless the variable is captured by an anonymous function (§12.16.6.2).
.....
So it's explicitly forbidden by the spec. As to why it's forbidden, for that you would have to ask the language designers, but considering how much complexity is involved in capturing variables, it is somewhat logical.
I guess the reason is simple: Too complex to compile.
There are 2 problems the compiler has to solve:
Generate a clourse for the anonymous method.
Synchronize the value of the variable.
Let's assume the following codes are valid.
unsafe void Function()
{
int length = 1;
void bar() => Console.WriteLine(length);
bar();
foo(&length);
bar();
}
unsafe void foo(int* i) { (*i)++; }
Expected result is:
1
2
To solve the first problem C# will generate an anonymous class to hold the upvalue.
Here is the pseudocode:
class _Anonymous
{
public int _length;
public void _bar() { Console.WriteLine(_length); }
}
unsafe void Function()
{
int length = 1;
var a = new _Anonymous { _length = length };
a._bar();
foo(&length);
a._bar();
}
To solve the second problem C# uses the generated field instead of the original local variable.
unsafe void Function()
{
//int length = 1;
var a = new _Anonymous { _length = 1 };
a._bar();
foo(&a._length);
a._bar();
}
These are all the works that a compiler can do. But till now the codes still won't work, we need an extra fixed block.
unsafe void Function()
{
var a = new _Anonymous { _length = 1 };
a._bar();
fixed (int* p = &a._length)
foo(p);
a._bar();
}
So the limitation can be removed with a smarter compiler, but things get more easy if we forbid such kind of codes.

Cycle in the struct layout that doesn't exist

This is a simplified version of some of my code:
public struct info
{
public float a, b;
public info? c;
public info(float a, float b, info? c = null)
{
this.a = a;
this.b = b;
this.c = c;
}
}
The problem is the error Struct member 'info' causes a cycle in the struct layout. I'm after struct like value type behaviour. I could simulate this using a class and a clone member function, but I don't see why I should need to.
How is this error true? Recursion could perhaps cause construction forever in some similar situations, but I can't think of any way that it could in this case. Below are examples that ought to be fine if the program would compile.
new info(1, 2);
new info(1, 2, null);
new info(1, 2, new info(3, 4));
edit:
The solution I used was to make "info" a class instead of a struct and giving it a member function to returned a copy that I used when passing it. In effect simulating the same behaviour as a struct but with a class.
I also created the following question while looking for an answer.
Value type class definition in C#?
It's not legal to have a struct that contains itself as a member. This is because a struct has fixed size, and it must be at least as large as the sum of the sizes of each of its members. Your type would have to have 8 bytes for the two floats, at least one byte to show whether or not info is null, plus the size of another info. This gives the following inequality:
size of info >= 4 + 4 + 1 + size of info
This is obviously impossible as it would require your type to be infinitely large.
You have to use a reference type (i.e. class). You can make your class immutable and override Equals and GetHashCode to give value-like behaviour, similar to the String class.
The reason why this creates a cycle is that Nullable<T> is itself a struct. Because it refers back to info you have a cycle in the layout (info has a field of Nullable<info> and it has a field of info) . It's essentially equivalent to the following
public struct MyNullable<T> {
public T value;
public bool hasValue;
}
struct info {
public float a, b;
public MyNullable<info> next;
}
The real problem is on this line:
public info? c;
Since this is a struct, C# needs to know the inner info/s layout before it could produce outer info's layout. And the inner info includes an inner inner info, which in turn includes an inner inner inner info, and so on. The compiler cannot produce a layout because of this circular reference issue.
Note: info? c is a shorthand for Nullable<info> which is itself a struct.
There isn't any way to achieve mutable value semantics of variable-sized items (semantically, I think what you're after is to have MyInfo1 = MyInfo2 generate a new linked list which is detached from the one started by MyInfo2). One could replace the info? with an info[] (which would always either be null or else populated with a single-element array), or with a holder class that wraps an instance of info, but the semantics would probably not be what you're after. Following MyInfo1 = MyInfo2, changes to MyInfo1.a would not affect MyInfo2.a, nor would changes to MyInfo1.c affect MyInfo2.c, but changes to MyInfo1.c[0].a would affect MyInfo2.c[0].a.
It would be nice if a future version of .net could have some concept of "value references", so that copying a struct wouldn't simply copy all of its fields. There is some value to the fact that .net does not support all the intricacies of C++ copy constructors, but there would also be value in allowing storage locations of type 'struct' to have an identity which would be associated with the storage location rather than its content.
Given that .net does not presently support any such concept, however, if you want info to be mutable, you're going to have to either put up with mutable reference semantics (including protective cloning) or with weird and wacky struct-class-hybrid semantics. One suggestion I would have if performance is a concern would be to have an abstract InfoBase class with descendants MutableInfo and ImmutableInfo, and with the following members:
AsNewFullyMutable -- Public instance -- Returns a new MutableInfo object, with data copied from the original, calling AsNewFullyMutable on any nested references.
AsNewMutable -- Public instance -- Returns a new MutableInfo object, with data copied from the original, calling AsImmutable on any nested references.
AsNewImmutable -- Protected instance -- Returns a new ImmutableInfo object, with data copied from the orignal, calling AsImmutable (not AsNewImmutable) on any nested references.
AsImmutable -- Public virtual -- For an ImmutableInfo, return itself; for a MutableInfo, call AsNewImmutable on itself.
AsMutable -- Public virtual -- For a MutableInfo, return itself; for an ImmutableInfo, call AsNewMutable on itself.
When cloning an object, depending upon whether one expected that the object or its descendants would be cloned again before it had to be mutated, one would call either AsImmutable, AsNewFullyMutable, or AsNewMutable. In scenarios where one would expect an object to be repeatedly defensively cloned, the object would be replaced by an immutable instance which would then no longer have to be cloned until there was a desire to mutate it.
Disclaimer: This may not achieve the goal of "struct like value type behaviour."
One solution is to use an array of one item to essentially get a reference the recursively referenced structure. Adapting my approach to your code looks something like this.
public struct info
{
public float a, b;
public info? c
{
get
{
return cArray[nextIndex];
}
set
{
steps[nextIndex] = value;
}
}
private info?[] cArray;
public info(float a, float b, info? c = null)
{
this.a = a;
this.b = b;
this.cArray = new info?[] { c }
this.c = c;
}
}

How to determine the size of an instance?

I have set my project to accept unsafe code and have the following helper Class to determine the size of an instance:
struct MyStruct
{
public long a;
public long b;
}
public static class CloneHelper
{
public unsafe static void GetSize(BookSetViewModel book)
{
long n = 0;
MyStruct inst;
inst.a = 0;
inst.b = 0;
n = Marshal.SizeOf(inst);
}
}
This works perfectly fine with a struct. However as soon as I use the actual class-instance that is passed in:
public unsafe static void GetSize(BookSetViewModel book)
{
long n = 0;
n = Marshal.SizeOf(book);
}
I get this error:
Type 'BookSetViewModel' cannot be marshaled as an unmanaged structure;
no meaningful size or offset can be computed.
Any idea how I could fix this?
Thanks,
Well, it really depends on what you mean by the "size" of an instance. There's the size of the single object in memory, but you usually need to think about any objects that the root object refers to. That's how much memory may be reclaimable after the root becomes eligible for garbage collection... but you can't just add them up, as those objects may be referred to by multiple other objects, and indeed there may be repeated references even within a single object.
This blog post shows some code I've used before to determine the size of the raw objects (header + fields), disregarding any extra cost due to the objects that one object refers to. It's not something I would use in production code, but it's useful for experimenting with how large an object is under varying circumstances.

C# Problem with class variable, unsafe/fixed pointer assignment

Ok, I have been into some circles now and though I might ask this at SO. I have a class lets say Class A with some member variables and functions. I have a portion of unsafe code to which I need to pass the member variable as a reference and assign some values to that reference variable.
Class A
{
int v1;
int v2;
....
public unsafe void Method(ref V)
{
// Here I need to have something like a
// pointer that will hold the address of V (V will be either v1 or v2)
// Assign some values to V till function returns.
int *p1 = &V
fixed (int *p2 = p1)
{
// Assign values.
}
}
}
The problem is as soon as the function returns, the values are not stored in either v1 or v2. So how do I fix this?
Thanks!
V is already pass-by-reference, so unless you have something specific in mind: just assign to V. Note that if multiple threads are involved here you might need volatile, Interlocked or synchronisation such as lock - and this applies to all access to the member (read or write).
You could simply pass the class variable (which would be by reference by default) and access its public fields/properties. Or you could:
Method(ref myA.v1);
public unsafe void Method(ref int V)
{
// Here I need to have something like a
// pointer that will hold the address of V (V will be either v1 or v2)
// Assign some values to V till function returns.
}
I can't imagine a compelling reason (with the details you gave) to actually need to fix v1 and v2 in memory and get their actually addresses to give to the function. Unless I've misunderstood?
EDIT:
Perhaps your assignment statements are missing a '*'? But again, why can't you just assign to the variables directly?
fixed (int *p2 = p1)
{
// Assign values.
*p2 = 42;
}

Categories

Resources