Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Safe (in the C# sense) way to implement something with pointers

Tags:

c#

pointers

            ...
            {
                int *r1, *r2;
                r1 = GetCorrectRegister(first);
                r2 = GetCorrectRegister(second);
                switch ((OpCode)current.opcode)
                {
                    case OpCode.ADDR:
                        r2 = r1 + r2;
                        break;
                }
            }
            ...

This is the obvious, easiest way to solve this problem. However, I'd prefer not to use an unsafe method if I can avoid it. Basically, I have a bunch of integers which represent registers. There are assembly instructions that take register mnemonics as arguments. I'd prefer not to have the logic to determine which variable to assign to in each branch of the switch statement or make some sort of kludgey GetRegisterValue(mnemonic) and SetRegisterValue(mnemonic) functions. Is there some C#y way to do something similar?

like image 644
Paul Avatar asked Feb 13 '11 07:02

Paul


People also ask

What is safe C?

The Maryland Safety Assessment for Every Child (SAFE-C) form (Attachment A) is a tool designed to alert staff to situations that pose an imminent danger to children.

Is C safe to use?

C and C++ are unsafe in a strong sense: executing an erroneous operation causes the entire program to be meaningless, as opposed to just the erroneous operation having an unpredictable result. In these languages erroneous operations are said to have undefined behavior.

What is a safe language?

Since memory safety bugs are often security issues, memory safe languages are more secure than languages that are not memory safe. Memory safe languages include Rust, Go, C#, Java, Swift, Python, and JavaScript. Languages that are not memory safe include C, C++, and assembly.


1 Answers

I have a bunch of integers which represent registers

The obvious thing here is not to have a bunch of integers. Create an array

 int[] registers = new int[NUMBER_OF_REGISTERS];

Your above code turns into

    {
            int r1Index, r2Index;
            r1Index = GetCorrectRegisterIndex(first);
            r2Index = GetCorrectRegisterIndex(second);
            switch ((OpCode)current.opcode)
            {
                case OpCode.ADDR:
                    registers[r1Index] = registers[r1Index] + registers[r2Index];
                    break;
            }


     }

Additionally, use an enum to create symbolic names for your register names where each name gives you the right index.

like image 146
Doc Brown Avatar answered Oct 03 '22 06:10

Doc Brown