Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 952815
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 15, 20262026-05-15T23:57:15+00:00 2026-05-15T23:57:15+00:00

This code causes the following exception, sometimes : Attempted to read or write protected

  • 0

This code causes the following exception, sometimes:

“Attempted to read or write protected
memory. This is often an indication
that other memory is corrupt”

private static TOKEN_GROUPS GetTokenGroups(IntPtr tokenHandle)
{
    var groups = new TOKEN_GROUPS();
    uint tokenInfoLength = 0;
    uint returnLength;

    var res = GetTokenInformation(tokenHandle, TOKEN_INFORMATION_CLASS.TokenGroups, IntPtr.Zero,
                                  tokenInfoLength, out returnLength);

    if (!res && returnLength > 0)
    {
        tokenInfoLength = returnLength;
        var tokenInfo = Marshal.AllocHGlobal((int) tokenInfoLength);
        res = GetTokenInformation(tokenHandle,
                                  TOKEN_INFORMATION_CLASS.TokenGroups,
                                  tokenInfo,
                                  tokenInfoLength,
                                  out returnLength);
        if(res)
        {
            groups = (TOKEN_GROUPS)Marshal.PtrToStructure(tokenInfo, typeof (TOKEN_GROUPS));
        }

        Marshal.FreeHGlobal(tokenInfo);
        CloseHandle(tokenHandle);
    }
    else
    {
        var error = new Win32Exception(Marshal.GetLastWin32Error());
        _log.WarnFormat("Failed evaluate the call to get process token information. {0}", error.Message);
    }
    return groups;
}

The line that fails is groups = (TOKEN_GROUPS)Marshal.PtrToStructure(tokenInfo, typeof (TOKEN_GROUPS)); I would say the exception happens in 1 and every 20 calls to this method. Once it begins happening every call afterwards will throw the exception. Restarting the process causes the error to go away.

IntPtr tokenHandle is the result of:

var processId = GetCurrentProcess();

            _log.InfoFormat("Process ID [{0}]", processId.ToString());

            if (processId != IntPtr.Zero)
            {
                IntPtr tokenHandle;
                if (OpenProcessToken(processId, TOKEN_READ, out tokenHandle))
                {
                    groups = GetTokenGroups(tokenHandle);
                }

EDIT Hopefully this isn’t information overload but here’s the pinvoke declarations:

     struct TOKEN_GROUPS
    {
        public uint GroupCount;
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4000)]
        public SID_AND_ATTRIBUTES[] Groups;
    }

    [StructLayout(LayoutKind.Sequential)]
    struct SID_AND_ATTRIBUTES
    {
        public IntPtr SID;
        public uint Attributes;
    }

    [DllImport("advapi32.dll", SetLastError = true)]
    static extern bool GetTokenInformation(
        IntPtr TokenHandle,
        TOKEN_INFORMATION_CLASS TokenInformationClass,
        IntPtr TokenInformation,
        uint TokenInformationLength,
        out uint ReturnLength);

    [DllImport("advapi32.dll", SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    static extern bool OpenProcessToken(IntPtr ProcessHandle,
        UInt32 DesiredAccess, out IntPtr TokenHandle);

    [DllImport("kernel32.dll")]
    static extern IntPtr GetCurrentProcess();

    enum TOKEN_INFORMATION_CLASS
    {
        TokenUser = 1,
        TokenGroups,
        TokenPrivileges,
        TokenOwner,
        TokenPrimaryGroup,
        TokenDefaultDacl,
        TokenSource,
        TokenType,
        TokenImpersonationLevel,
        TokenStatistics,
        TokenRestrictedSids,
        TokenSessionId,
        TokenGroupsAndPrivileges,
        TokenSessionReference,
        TokenSandBoxInert,
        TokenAuditPolicy,
        TokenOrigin
    }
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-15T23:57:16+00:00Added an answer on May 15, 2026 at 11:57 pm

    My guess is that the error is a result of not correctly freeing up resources, as is the case in your situation. I may be wrong in it being the cause, but it’s probably a good idea to wrap the FreeHGlobal and CloseHandle in a finally block, to ensure proper cleaning up.

    If the error then persists, it might be something else (wrong structure or wrong data layout in the declaration or wrong LayoutKind for TOKEN_GROUPS?) or wrong use of this particular API (which I’m not too familiar with).

    Edit (after your edit)

    The problem may very well lay in the necessary SizeConst attribute parameter. Consider the following: the GetTokenInformation has given the size returned in tokeInfoLength. You allocate this. This size is not likely equal to the SizeConst value. If SizeConst is larger than the required size, the Marshal.PtrToStructure will access further then the length that you allocated, because it knows only SizeConst, and this memory may be accessible, and may be not.

    To resolve this issue, make sure that the AllocHGlobal call is at least the size of the whole structure as marshalled. Try, for instance, to add 4000 and see if the error returns (other, neater solutions exist, but let’s keep it simple for a moment).

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Why does the following code sometimes causes an Exception with the contents CLIPBRD_E_CANT_OPEN: Clipboard.SetText(str);
I have the following code: if (include_once(dirname(__FILE__).'/file.php') || include_once(dirname(__FILE__).'/local/file.php') ) { This causes an
Sometimes bugs can cause memory access violation exception. How exactly this exception is triggered?
I have the following code. My intention that this custom object can be cast
Exception org.hibernate.exception.LockAcquisitionException: could not insert appears sometimes in the following code: Question questionClone; try
I'm in troubles with TransactionPropagation.NotSupported. I believed that this propagation causes that the code
This code causes a Segmentation Fault: int main(){ char *p; char a[50] = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;
Does this code cause a memory leak: int main(){ int * a = new
I have this code: <script id=toModify > Invalid javascript that will cause errors </script>
This code is the core of a much larger script that works great in

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.