Fixed Statement in C#
Asked Answered
P

5

12

We have similar code to the following in one of our projects. Can anyone explain (in simple English) why the fixed statement is needed here?

class TestClass
{
    int iMyVariable;
    static void Main()
    {
        TestClass oTestClass = new TestClass();
        unsafe
        {
            fixed (int* p = &oTestClasst.iMyVariable)
            {
                *p = 9;
            }
        }
    }
}
Portal answered 30/9, 2008 at 14:44 Comment(0)
F
17

It fixes the pointer in memory. Garbage collected languages have the freedom to move objects around memory for efficiency. This is all transparent to the programmer because they don't really use pointers in "normal" CLR code. However, when you do require pointers, then you need to fix it in memory if you want to work with them.

Filberte answered 30/9, 2008 at 14:49 Comment(0)
N
9

The fixed statement will "pin" the variable in memory so that the garbage collector doesn't move it around when collecting. If it did move the variable, the pointer would become useless and when you used it you'd be trying to access or modify something that you didn't intend to.

Namedropper answered 30/9, 2008 at 14:48 Comment(0)
C
7

You need it anywhere you do pointer arithmetic, to prevent the garbage collector from moving it around on you.

Callant answered 30/9, 2008 at 14:47 Comment(2)
i don't see any pointer arithmetic being done in the question. perhaps you can clarify what you mean by 'arithmetic'. there's no + - * nor /.Whooper
I used the "pointer arithmetic" term more broadly, to mean "operations done on a pointer".Callant
A
2

Because you are running in unsafe mode (pointer), the fixed instruction allocate a specific memory space to that variable. If you didn't put the fixed instruction, the garbage collector could move in memory the variable anywhere, when he want.

Hope this help.

Albert answered 30/9, 2008 at 14:48 Comment(0)
V
2

MSDN has a very similar example. The fixed statement basically blocks garbage collection. In .Net if you use a pointer to a memory location the runtime can reallocate the object to a "better" location at any time. SO if you want to access memory directly you need to fix it in place.

Vonnievonny answered 30/9, 2008 at 15:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.