在释放非托管内存时,为什么“堆上的损坏”错误消息

时间:2014-01-15 15:49:41

标签: c# free unmanaged

我的C#项目中有一段代码片段如下:

CK_ATTRIBUTE findTemplate = new CK_ATTRIBUTE();                                                 

findTemplate.type = CKAT_USER_NAME;
findTemplate.pValue = new IntPtr();
findTemplate.pValue = Marshal.AllocHGlobal(MAX_USERID_LENGTH);
Marshal.Copy(sUserName, 0, findTemplate.pValue, MAX_USERID_LENGTH);
findTemplate.ulValueLen = MAX_USERID_LENGTH;

IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(CK_ATTRIBUTE)));
Marshal.StructureToPtr(findTemplate, ptr, false);

/*Call pinvoke function here which modifies ptr*/

Marshal.PtrToStructure(ptr, findTemplate);

byte[] userIdBytes = new byte[findTemplate.ulValueLen];

Marshal.Copy(findTemplate.pValue, userIdBytes, 0, (int) findTemplate.ulValueLen);
adminKeyName = System.Text.Encoding.ASCII.GetString(userIdBytes);

Marshal.FreeHGlobal(findTemplate.pValue); //this causes error                         
Marshal.FreeHGlobal(ptr); //this does not

CK_ATTRIBUTE是一个具有顺序布局的结构,其成员类型为(String)pValue(IntPtr)和ulvaluelen(int)

为什么第一次释放时会出现“堆上的损坏”错误消息?

我正在进行排序的功能定义如下:

[DllImport("sduserSES.dll", CallingConvention = CallingConvention.Cdecl)]
            static extern uint C_GetAttributeValue(uint hSession,   /* the session's handle */
                                                  uint hObject,    /* the object's handle */
                                                  IntPtr pTemplate,  /* specifies attributes, gets values */
                                                  uint ulCount     /* attributes in template */
                                                  );

0 个答案:

没有答案