读书人

字符数组给string赋值报stack overflo

发布时间: 2012-04-08 14:38:30 作者: rapoo

字符数组给string赋值报stack overflow是什么问题?

Delphi(Pascal) code
var  i, iSize: Integer;  SourceId: Cardinal;  szValue1: PChar;//array[0..MAX_PATH - 1] of Char;  szValue2: PChar;//array[0..MAX_PATH - 1] of Char;  sValue1, sValue2: string;begin  iSize := MAX_PATH * SizeOf(Char);  szValue1 := GetMemory(MAX_PATH * SizeOf(Char));  szValue2 := GetMemory(MAX_PATH * SizeOf(Char));  try    for i := 0 to AList.Count - 1 do    begin      ZeroMemory(szValue1, iSize);      if SetupGetSourceFileLocation(AInf, nil, PChar(AList.Strings[i]),        SourceId, szValue1, MAX_PATH, nil) then      begin//        sValue1 := szValue1;        SetLength(sValue1, lstrlen(szValue1));        CopyMemory(@sValue1[1], szValue1, lstrlen(szValue1) * SizeOf(Char));        ZeroMemory(szValue2, iSize);        if SetupGetSourceInfo(AInf, SourceId, SRCINFO_PATH, szValue2,          MAX_PATH, nil) then        begin//          sValue2 := szValue2;             //第二次循环时,此处报错,不管是直接赋值还是用CopyMemory,字符szValue为Char数组和PChar都试过。          SetLength(sValue2, lstrlen(szValue2));          CopyMemory(@sValue2[1], szValue2, lstrlen(szValue2) * SizeOf(Char));        end        else          szValue2 := '';        OutputDebugString(PChar(sValue2 + '\' + sValue1));      end;    end;  finally    FreeMemory(szValue1);    FreeMemory(szValue2);  end;end;


SetupGetSourceFileLocation和SetupGetSourceInfo可查看msdn

[解决办法]
内存搞乱了。既然使用了string类型变量sValue1, sValue2;就不需要使用copymemory。而且你这样copymemory也不对。
为什么你把“sValue1 := szValue1”注释掉,而改用那种方式?
[解决办法]
Move(szValue1^,szValue2^,len);

读书人网 >.NET

热点推荐