Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[BUG] CRepr zero-sized structs aren't zero-sized #2201

Open
zerkawei opened this issue Mar 27, 2025 · 0 comments
Open

[BUG] CRepr zero-sized structs aren't zero-sized #2201

zerkawei opened this issue Mar 27, 2025 · 0 comments

Comments

@zerkawei
Copy link
Contributor

zerkawei commented Mar 27, 2025

Marking a zero-sized struct with CRepr adds a byte to it making its size no longer 0.

[CRepr]
public struct Foo {}
sizeof(Foo); // 1

I encountered this bug when trying to use System.Net.Socket where SockAddr_in inherits from SockAddr and therefore is offset by a byte and it breaks bind.

Here's a repro to observe the bug in action.

using System;
namespace Repro;

[CRepr]
public struct Foo {}

[CRepr]
public struct Bar : Foo
{
	public uint8 value1;
	public uint8 value2;
}

[CRepr]
public struct FooBar
{
	public uint8 value1;
	public uint8 value2;
}

public class Program
{
	public static void Main()
	{
		Bar bar;
		bar.value1 = 1;
		bar.value2 = 2;
		Console.WriteLine("bar : {}, {}", bar.value1, bar.value2); // bar : 1, 2

		FooBar foo = *(FooBar*)&bar;
		Console.WriteLine("foo : {}, {}", foo.value1, foo.value2); // foo : 0, 1

		Console.Read();
	}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant