VC++动态分配内存出错解决方法

来源:互联网 发布:海森堡测不准原理 知乎 编辑:程序博客网 时间:2024/06/05 09:06

问题描述:

我做了一个tcp发包和接包的函数,但是运行之后,总是报错,错误如下:

 

 

我的函数代码如下:

void CThreadTestDlg::sendmsg() throw()

{

         TcpBase* tcpb=newTcpBase();

         //tcpb=(TcpBase*)malloc(2048);

         SOCKET sc=tcpb->SocketCreate();

         CString medata;

         CString medataint;

         CString medatasend;

 

         tip->GetWindowText(medata);

 

         hsmip=(char*)medata.GetBuffer();

 

         tport->GetWindowText(medataint);

         hsmport=_ttoi(medataint);

         tthnum->GetWindowText(medataint);

         testthnum=_ttoi(medataint);

         tfornum->GetWindowText(medataint);

         testfornum=_ttoi(medataint);

         try{

                   tsend->GetWindowText(medatasend);

                   sendstr=(char*)medatasend.GetBuffer();

 

                   tcpb->Connect(sc,hsmip,hsmport);

                   tcpb->Send(sc,sendstr,2);

                   intbodysize=tcpb->Recieve(sc,2);

                   revstr = (char*)malloc(bodysize);

                   //revstr=newchar[1024];

                   tcpb->Recieve(sc,revstr,bodysize);

 

                   trev->SetWindowText(revstr);

 

                   tcpb->DisConnect(sc);

         }catch(CException*er)

         {

                   er->Delete();

         }

         //free(tcpb);

}

 

过程描述:

1.这个问题我在网上查资料,很少有相关的描述

2.询问技术群的群友,得到的答案是内存越界等等,但是怎么解决还是没有眉目

3.查询手上的资料,也没有相关的具体问题和解决办法

4.最后,我只能用自己的杀手锏了,一步一步跟踪了,最后发现是下面这两条语句引起来的

                   revstr = (char*)malloc(bodysize);

                   tcpb->Recieve(sc,revstr,bodysize);

再看看内存分配的相关资料,指针初始化使用malloc方法分配内存不能用在堆栈内,要使用堆栈内存分配方法,如下:

       revstr=newchar[1024]

 

 

问题解决:

给指针进行堆栈内内存分配,再运行代码,一切ok

 

代码如下:

void CThreadTestDlg::sendmsg() throw()

{

         TcpBase* tcpb=newTcpBase();

         //tcpb=(TcpBase*)malloc(2048);

         SOCKET sc=tcpb->SocketCreate();

         CString medata;

         CString medataint;

         CString medatasend;

 

         tip->GetWindowText(medata);

 

         hsmip=(char*)medata.GetBuffer();

 

         tport->GetWindowText(medataint);

         hsmport=_ttoi(medataint);

         tthnum->GetWindowText(medataint);

         testthnum=_ttoi(medataint);

         tfornum->GetWindowText(medataint);

         testfornum=_ttoi(medataint);

         try{

                   tsend->GetWindowText(medatasend);

                   sendstr=(char*)medatasend.GetBuffer();

 

                   tcpb->Connect(sc,hsmip,hsmport);

                   tcpb->Send(sc,sendstr,2);

                   intbodysize=tcpb->Recieve(sc,2);

                   //revstr= (char*)malloc(bodysize);

                   revstr=new char[1024];

                   tcpb->Recieve(sc,revstr,bodysize);

 

                   trev->SetWindowText(revstr);

 

                   tcpb->DisConnect(sc);

         }catch(CException*er)

         {

                   er->Delete();

         }

         //free(tcpb);

0 0