首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

线程函数 指针返回有关问题

2013-08-04 
线程函数 指针返回问题我定义了一个类,开辟一个线程操作一块内存,将数据写入内存,但是我调用这个类的时候,

线程函数 指针返回问题
我定义了一个类,开辟一个线程操作一块内存,将数据写入内存,但是我调用这个类的时候,无法获取内存中的数据?
弹出错误:
  Win32.exe 中的 0x00433a76 处有未经处理的异常: 0xC0000005: 读取位置 0x0114ff58 时发生访问冲突

TestThreadMemory.h


#pragma once
class CTestThreadMemory
{
public:
typedef struct{
 double FromX;
 double FromY;
 double ToX;
 double ToY;
 HANDLE hMutex;
 long  NumberTotal;
 int ***TotalData;
}MyTheadParams;
MyTheadParams mythreadparams;
public:
CTestThreadMemory(void);
~CTestThreadMemory(void);
public:
   static DWORD _stdcall SecondThreadMemory(LPVOID lparam);
   void testmemory();
};


TestThreadMemory.cpp

#include "StdAfx.h"
#include "TestThreadMemory.h"
#include <windows.h>
#include <process.h>
#include <stdio.h>

CTestThreadMemory::CTestThreadMemory(void)
{
mythreadparams.TotalData=new int **[2];
mythreadparams.hMutex=CreateMutex(NULL, FALSE, NULL);
}


CTestThreadMemory::~CTestThreadMemory(void)
{
}
DWORD  _stdcall CTestThreadMemory::SecondThreadMemory(LPVOID lparam)
{
 CTestThreadMemory::MyTheadParams *threadparams=( CTestThreadMemory::MyTheadParams *)lparam;
  WaitForSingleObject(threadparams->hMutex, INFINITE);
 threadparams->FromX=12345.789;
int *data=(int*)malloc(sizeof(int)*4);
ZeroMemory(data, sizeof(int)*4);
 int *m=(int*)malloc(sizeof(int));
     ZeroMemory(m, sizeof(int)) ;
 *m=789;
 //*****将数据写入到内存
 for(int i=0;i<2;i++)
 {
 *m=198+i;
 memcpy((int*)data+i,m,sizeof(int));
 }

 //******内存数据读出,输出
 static char buf1[30];
    // _snprintf(buf1,29,"%d%d%d",*data,*(data+1),*(data+2));buf1[29]=0;
// int**pp=NULL;
// pp=&data;         //*******将data转化为二级指针

  int u=2;
  int ***p3;
  p3=new int**[u];
  p3[0]=&data;
  p3[1]=NULL;

  threadparams->TotalData=p3;

// _snprintf(buf1,29,"%d",*(data+1));buf1[29]=0;  // *****利用一级指针打印输出
// _snprintf(buf1,29,"%d",*(*pp+1));buf1[29]=0;     //******利用二级指针打印输出
   _snprintf(buf1,29,"%d",*(*p3[0]+1));buf1[29]=0; //*****利用二级指针数组 这里是正确的!!!!!!!!!!


    ReleaseMutex(threadparams->hMutex);
   return 0;
}

void CTestThreadMemory::testmemory()
{
HANDLE hThread=  (HANDLE)_beginthreadex(NULL,0,(unsigned(_stdcall *)(void *))SecondThreadMemory,&mythreadparams,0,NULL);
WaitForSingleObject(   hThread,   INFINITE   );   
    CloseHandle(   hThread   );  

}



类的调用
void  testmemeoryclass()
{
CTestThreadMemory  ctestthreadmemory;
 ctestthreadmemory.testmemory();

 CTestThreadMemory::MyTheadParams  *getparams=&ctestthreadmemory.mythreadparams;

 int ***ppp=getparams->TotalData;

 int **pp=getparams->TotalData[0];
 char buf1[30];

  _snprintf(buf1,29,"%d",*(*ppp[0]+1));buf1[29]=0; //错误!这里 !!!!!!!!!!输出一个数据测试下,类里面输出时正常的
}



纠结好久了 ,为什么???????最后一部步了,大侠们 跪求
[解决办法]
data 是一个局部变量, 函数结束, 变量就无效了. 用 &data 取出来的地址是不能长久保存的.

p3[0]=&data;

改成

p3[0]= new int*(data);

即可正常运行.

热点排行