char* ch = new char[nCount];
         //执行一些操作对ch
  delete[] ch;
由于要在程序运行的时候动态开一个数组,所以写了上面的代码。我知道用了new之后就一定要delete,可是每次执行到最后那句话,就会弹出window最有名的那个带有“大红叉”的对话框,就是有“终止,重试,忽略”三个按钮的那个,感觉好像是对内存的非法操作,别的我就不知道了。
往各位大虾不吝赐教。

解决方案 »

  1.   

    单从这两步来说是没有错误的,最终出现“大红叉”的原因应该是中间对ch的操作。你应该重点检查一下有没有对ch的越界操作(即使用了超出分配空间的内存),这是问题的多发点。
      

  2.   

    CString CMy11123Dlg::Encrypt(CString strSource, int iKey)
    { char chTemp[255];
    CString str;
    char* ch = new char[strSource.GetLength()];
    wsprintf(chTemp, "%s", strSource);
    for(int i = 0; i <= strSource.GetLength(); i++)
    ch[i] = chTemp[i] + iKey;
    str.Format("%s", ch);
    //delete [] ch;
    return str;}
    整个函数我都贴出来了,麻烦各位给看看,先鞠躬了。
      

  3.   

    char* ch = new char[nCount];
             //执行一些操作对ch
      delete[] ch;
    错误肯定在 //执行一些操作对ch 中,可能改变了ch的值,也可能ch已被释放,还可能是这段代码执行了非法操作(比如内存操作超出范围,改变了new所保存的一些重要信息。
      

  4.   

    CString CMy11123Dlg::Encrypt(CString strSource, int iKey)
    { char chTemp[255];
    CString str;
    char* ch = new char[strSource.GetLength()];
    //此句最好改为 char* ch = new char[strSource.GetLength()+1];
    wsprintf(chTemp, "%s", strSource);
    for(int i = 0; i <= strSource.GetLength(); i++)
    //这儿i应该为i<strSource.GetLength().
    ch[i] = chTemp[i] + iKey;
    str.Format("%s", ch);
    //本句有错。ch所指的字符串必须以'\0'结尾,显然不一定是。
    //可在本句前加上 if(i>0) ch[i-1]='\0';
    //delete [] ch;
    //本句不应该注释掉。
    return str;}
      

  5.   

    char* ch = new char[strSource.GetLength()]这句少分配了一个字节,给字节用于存储字符串结束符'\0',应改为:char* ch = new char[strSource.GetLength()+1]
      

  6.   

    coohai(海) :
      呵呵,老兄更仔细,不错!
      

  7.   

    哥们,for(int i = 0; i <= strSource.GetLength(); i++)一句中
    中间的<=改为<
      

  8.   

    LaoLi_SC_008(力):
      大家都不错!
      

  9.   

    佩服佩服,一段简单的加密代码楼主写得如此复杂和效率底下.这样就可以了.
    CString CMy11123Dlg::Encrypt(CString strSource, int iKey)
    {
       CString strResult = strSource;
       for(int i = 0; i < strSource.GetLength(); i++)
       {
          strResult.SetAt(i, strSource[i] + iKey);
       }
       return strResult;
    }
     
    如果需要效率更高的话,可以将函数定义为
    void CMy11123Dlg::Encrypt(CString& strSource, int iKey)
    {
      for(int i = 0; i < strSource.GetLength(); i++)
       {
          strSource.SetAt(i, strSource[i] + iKey);
       }
    }
      

  10.   

    coohai(海) :
    你说的都很对,只是最后的ch[i-1]应该变成ch[i]。
    ilovevc(ilovevc):
    你让我知道了函数SetAt的用法,真是方便。
    我原来不知道字符串和ASC之间的关系,所以才写了个这样的函数来试试,再加上开始想用C写,但因为功力不够结果就变成这样的不伦不类了。
    好在现在又知道了一点,类型char这样敷值是没有'\0'的。最后,给大家鞠躬了,分太少,没法都给了。