【问题标题】:Access violation error with the new command新命令的访问冲突错误
【发布时间】:2012-02-27 02:39:41
【问题描述】:

我正在为我的 GUI 编程课做一个作业,我们将在其中制作一个 Windows 程序,以十六进制显示文件的内容。我有一个包含文本并以字符串格式创建十六进制的类。

我正在尝试创建一个字符数组来存储每一行​​以供输出。但是,当我使用 new 创建字符指针数组时,出现访问冲突错误。

我进行了一些搜索,但没有找到答案。

该类有这些成员变量:

char* fileText;   
char** Lines;
int numChars;  
int numLines;  
bool fileCopied;

我的构造函数:

Text::Text(char* fileName){  //load and copy file.
   fileText = NULL;
   Lines = NULL;
   fileCopied = ExtractText(fileName);
   if ( fileCopied ) {
      CreateHex();
   }//endif
}//end constructor 

ExtractText 加载给构造函数的文件,并将其复制到一个大字符串中。

bool Text::ExtractText(char fileName[]){
   char buffer = '/0';    //buffer for text transfer
   numChars = 0;              //initialize numLines
   ifstream fin( fileName, ios::in|ios::out );  //load file stream
   if ( !fin ) {     //return false if the file fails to load
      return false;
   }//endif

   while ( !fin.eof() ) {      //count the lines in the file
      fin.get(buffer);
      numChars++;
   }//endwh

   fileText = new char[numLines];  //create an array of strings, one for each line in the file.

   fin.clear();           //clear the eof flag
   fin.seekg(0, ios::beg); //move the get pointer back to the start of the file.

   for ( int i = 0; i < numChars; i++ ) { //copy the text from the file into the string array.
      fin.get(fileText[i]);
   }//endfr
   fileText[numChars-1] = '\0';
   fin.close();
   numLines = (numChars % 16 == 0) ? (numChars/16) : (numChars/16 + 1);
   return true;
}//end fun ExtractText

然后是问题代码。在 CreateHex 函数中,第一行是尝试创建字符指针数组的位置。

void Text::CreateHex(){
    Lines = new char*[numLines];

程序一运行那行代码,就会出现访问冲突。我不太确定问题出在哪里,因为我之前在之前的程序中使用过完全相同的方法。唯一的区别是指针的名称。如果这有什么不同,我正在使用 Borland C++ 5.02。这不是我在编译器中的首选,但它是我们老师希望我们使用的。

【问题讨论】:

    标签: c++ access-violation new-operator


    【解决方案1】:

    当你执行该行时

    fileText = new char[numLines]
    

    变量 numLines 尚未初始化。作为一个成员变量,它被初始化为0,所以你为fileText分配了一个空数组。

    【讨论】:

    • NumLines 在 ExtractText 的末尾设置为文件中 16 个字符的行数。
    • 确实,但那是在使用之后!
    • CreateHex 仅在 ExtractText 完成后运行。 numLines 在 ExtractText 的末尾设置为正的非零值。看构造函数。 ExtractText 运行,如果它返回 true,则 CreateHex 运行。如果 ExtractText 返回 true,则 numLines 的值必须至少为 1,除非我尝试加载空白文件,但这不是我遇到的问题。我可以向您保证,并且我已经通过调试验证了 numLines 在使用时具有一个正的非零值。
    • 我的意思是在函数 ExtractText 的中途使用 numLines,而不是 CreateHex 中的那个。
    • 我完全忽略了那个,因为那段代码执行没有问题。这是一些重复使用的代码,ExtractText 中的数组应该使用 numChars。但是,我认为这实际上是导致访问冲突的原因,因为当我更改它时,CreateHex 运行时没有错误。我想这只是表明引发错误的行并不总是罪魁祸首。
    猜你喜欢
    • 2015-07-29
    • 1970-01-01
    • 2018-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-28
    相关资源
    最近更新 更多