动态内存分配,正在读取中的文件

Dynamic Memory Allocation with reading file in

本文关键字:读取 文件 内存 分配 动态      更新时间:2023-10-16

我正在尝试为这个项目使用动态内存。我犯了一个seg错误,但我不知道我做错了什么。有人能指出我的错误在哪里吗?文件似乎读取正确。。。但我认为错误是一个无赖的指针。。帮助

我只是想从一个文件中读"心二2"到"王牌11",所有的单词都用空格隔开。我的程序在使用动态内存之前就工作了。。

#include <iostream>
#include <fstream>
#include <ctime>
#include <stdlib.h>
#include <string>
using namespace std;
//global constant(s)
const int maxCards = 52;
//Structs
struct card 
{
    char *suit;
    char *rank;
    int cvalue;
    char location;
};
void readDeck(card* deckPtr);
void cardsInit(char *finNameP,card *deckPtr);
//program
int main()
{
  card *deckPtr = new card[52];
  char *finNameP = new char[13];
  strcopy(finNameP,"cardFile.txt");
  cardsInit(finNameP,deckPtr); // function i wrote that works
  readDeck(deckPtr); //simply reads the deck from &deckPtr[0] -> &deck[51]
  delete [] finNameP;
}
void cardsInit(char *finNameP, card *deckPtr)
{
  //set up card file to be read in
  ifstream fin;
  cout << "Please enter file name...(cardFile.txt)" << endl;;
  cin >> *finNameP;
  fin.open(finNameP);
  //create pointer and set initial value
  card *deckHome = deckPtr;
  for(int i=0;i<52;i++)
  {
    (*deckPtr).suit = new char[9];
    (*deckPtr).rank = new char[9];
    deckPtr++;
  }
  deckPtr = deckHome;
  //check if cardFile.txt opens correctly
  if(!fin.good())
  {
    cout << "Error with card file" << endl;  
  }
  else
  {
    while(fin.good())
    {
      for(deckPtr = &deckPtr[0]; deckPtr < &deckPtr[maxCards];deckPtr++)
      {
        fin >> (*deckPtr).suit;
        fin >> (*deckPtr).rank;
        fin >> (*deckPtr).cvalue;
      }   
    }    
  } 
  fin.close();    
  delete []finNameP;
  delete [] (*deckPtr).suit;
  delete [] (*deckPtr).rank;
}

这是一种非常古老的编程方式。不要使用new,而是使用std::stringstd::vector<char>。它们也使用动态内存,但它们会使您更难意外地导致内存分配错误。

第一个问题出现在这里:

cin >> *finNameP; 

由于finNameP具有类型char *,则*finNameP具有类型char。所以这个指令只读取一个字符。然后继续执行fin.open(finNameP);,这会导致未定义的行为,因为finNameP中没有字符串。

最简单的修复方法是将finNameP设为std::string。请注意,执行cin >> finNameP(不更改类型)将进行编译,但这不是一个好主意,因为没有缓冲区溢出保护。您可以编写cin >> setw(12) >> finNameP;,但这仍然比使用字符串差得多。

deckPtr < &deckPtr[maxCards]始终为true,for循环将永远运行。