PChar在StrPLCopy上的无效指针操作

时间:2011-05-21 17:37:52

标签: delphi delphi-2010 winsock winsock2 winsockets

我在WinSock 2中编写了一些TCP服务器,并且我捕获了FD_READ事件的hava程序。在这个过程中,我需要解析收到的消息。代码在这里:

procedure TfrmMain.WndProc_OnWSANetEvent(var Msg: TMessage);
Var
  iCurrThread, n : Integer;
  i : Integer;
  temp : PChar;
  len : Integer;
  params : PChar;
  username : PChar; password : PChar;
  ind : Integer;
  tempy : PChar;
  tempn : PChar;
begin
  case WSAGetSelectEvent(Msg.LParam) of
    FD_READ :
      while True do
      begin
        if (FreeRThreads.GetCount <> 0) then
          begin
            iCurrThread := FreeRThreads.Pop;
            if (ReadThreads[iCurrThread].Terminated) then
              begin
                ReadThreads[iCurrThread].SetFSocket(Msg.WParam);
                ReadThreads[iCurrThread].Execute;

                temp := ReadThreads[iCurrThread].GetFText;
                meLog.Lines.Add(temp);

                if (copy(temp,1,2)='AU') then
                  begin
                    StrPLCopy(params, PChar(copy(temp, 7, StrToInt( copy(temp, 3, 4) ) )), 16372);
                    ind := pos(' ', params);
                    StrPLCopy(username, PChar(copy(params, 1, ind-1)), 16372);
                    StrPLCopy(password, PChar(copy(params, ind + 1, StrLen(params))), 16372);

                    StrPLCopy(tempy, PChar('AU0001y'), 14);
                    StrPLCopy(tempn, PChar('AU0001n'), 14);

                    if (username=PChar('dizpers')) then
                      if (password=PChar('admin')) then
                        send(Msg.WParam, tempy^, 14, 0)
                      else
                        send(Msg.WParam, tempn^, 14, 0)
                    else
                      send(Msg.WParam, tempn^, 14, 0);

                    meLog.Lines.Add('USER = '+username);
                    meLog.Lines.Add('PASSWORD = '+password);
                  end;



                FreeRThreads.Push(iCurrThread);
                break;
              end;
          end;
      end;
    FD_CLOSE :
      begin
        n := CSocketsCount - 1;
        for i := 0 to n do
          if (ClientSockets[i] = Msg.WParam) then
            begin
              closesocket(ClientSockets[i]);
              FreeSockets.Push(i);
              break;
            end;
      end;
  end;
end;

调试时我在行

上有“Acces Violation ...写地址......”
StrPLCopy(params, PChar(copy(temp, 7, StrToInt( copy(temp, 3, 4) ) )), 16372);

Plz,帮我解决这个问题并理解它为什么会发生。 TIA!

1 个答案:

答案 0 :(得分:4)

在使用StrPLCopy之前,您必须为params变量分配内存(同样适用于usernamepasswordtempy,{{1} })

检查此示例

tempn