2012-06-16 4 views
1

while 루프 내에 스위치가 있습니다. 옵션 4를 세 번 호출하면 다음 번에 int를 입력 할 때 프로그램이 충돌하여 어떤 경우에 스위치를 사용할 것인지 결정합니다. 나는 그것이 왜 일어나는 지 전혀 모른다. 세 후while-switch 루프에서 istream 크래시가 발생했습니다.

void Menu::start() 
{ 
    Store st; 
    int op=1,num,quantity; 
    string name; 
    while(op!=0) 
    { 
     cin>>op; 
     try 
     { 
      switch(op) 
      { 
        case 1: 
      { 
       cin>>num>>name; 
       st.addProduct(num,name); 
       break; 
      } 
      case 4: 
       { 
        cin>>num>>quantity; 
        st.sellProduct(num,quantity); 
        break; 
       } 
      case 0: 
       break; 
      default: 
       throw(exception("Unknown option, try again.\n")); 
      } //end of switch 
     } //end of try 
//catches 
    } //end of while 
} 

/***************************************************************************** 
* function name: addProduct 
* The Input: This Store, const& int num, const& string name 
* The output: If product with given num doesn't exist in store, adds it to 
* store. 
* The Function operation: uses the products map. 
*****************************************************************************/ 
void Store::addProduct(const int& num,const string& name) 
{ 
    //if product doesn't exist in map, add it 
    if(prods.find(num)==prods.end()) 
     prods.insert(pair<int,Product>(num,Product(num,name))); 
    //otherwise issue an error 
    else 
     throw(AddProdException(num)); 
} 

/***************************************************************************** 
* function name: sellProduct 
* The Input: This Store, const int& prodNum, const unsigned int& quantityBought 
* The output: If product doesn't exist or quantityBought is more than 10 units 
* more than quantity in stock, issues an error. Otherwise, sells the product 
* and if needed, issues a shipment such that after the purchase the store will 
* be left with 20 units. 
* The Function operation: uses the products and orders map. 
*****************************************************************************/ 
void Store::sellProduct(const int& prodNum, const unsigned int& quantityBought) 
{ 
    if(prods.find(prodNum)!=prods.end()) 
    { 
     Product& pr = prods.find(prodNum)->second; 
     const int& signedQB=quantityBought, signedPQ=pr.getQuantity(); 
     if(signedPQ<signedQB-10) 
      //store can't supply product 
      throw(BuyQuanException(prodNum,quantityBought)); 
     //make purchase 
     else 
     { 
      //purchase only what left in stock 
      if(signedPQ<signedQB) 
      { 
       //issue shipment 
       Order order=Order(prodNum,20+quantityBought-pr.getQuantity()); 
       orders.insert(pair<int,Order>(order.getID(),order)); 
       //document order 
       purchaseDocs.add(new Documentation(pr,quantityBought, 
        orders.find(order.getID())->second)); 
       //buy product 
       pr.decreaseQuantity(pr.getQuantity()); 
      } 
      //purchase requested amount 
      else 
      { 
       //buy product 
       pr.decreaseQuantity(quantityBought); 
       //document order 
       purchaseDocs.add(new Documentation(pr,quantityBought)); 
      } 
     } //else regarding making the purchase 

    } //if regarding found the product 
    //otherwise issue an error 
    else 
     throw(BuyProdException(prodNum)); 
} 

가 (단지 3 시간 후, 전용 케이스 (4)과 4), 사례 위해 입력, 그것은 내부가 CIN >> OP 도달 다음번 충돌 : 이 while 루프의 코드는 istream 파일. 오류로 인해 다음과 같은 오류 메시지가 나타납니다. "Ex6.exe의 0x4a34870c에서 처리되지 않은 예외 : 0xC0000005 : 액세스 위반." 도움을 환영 할 것입니다!

+0

그냥 추측하면 C++ 11을 사용하지 않습니까? ;; 어쨌든, 당신은 [valgrind] (http://valgrind.org)가 그것을 봐야합니다. –

+0

"크래시"란 무엇을 의미합니까? 또한, 여기에 게시하기 전에 코드를 최소한으로 줄이십시오. 그리고 우리에게 최강의 * compilable * 코드를 제공하십시오. 게시 된 코드에는 모를 물건이 많이 포함되어 있으므로 문제를 재현 할 수 없습니다. –

+0

업데이트 된 질문. 그리고 Jonas, C++ 11을 사용하지 않습니다. – nodwj

답변

3

이 :

const char* errStr=e.what(); 
cout<<errStr; 
//errStr is a dynamically allocated string we don't need anymore <----------- 
delete[] errStr; 

나쁜 가정입니다. std::exception::what에 의해 반환 된 const char*은 동적으로 할당되지 않으며 예외에 내부적으로 할당 된 문자열에 대한 포인터 일뿐입니다. 은 해당 포인터를 삭제하면 안됩니다. 코드에 다른 오류가있을 수 있지만이를 수정해야합니다.

+0

나는 당신의 요지를 얻었지만, 그것은 단지 내 예외 (ProductException)에서 errStr가 동적으로 할당되었다. 그래서 메모리 누수를 막기 위해 그것을 삭제해야한다. 그렇지 않습니까? – nodwj

+0

해당 예외의 정의를 제공해야합니다. 나는 당신의 예외가'std :: exception'을 상속 받았다고 가정했다. (당신이'ProductException :: what()'을 호출 한 이후로 논리적으로 보임). – mfontanini

+2

@ 아이 단 : 그런 경우 예외가 복사 가능하고 복사 할 때 올바르게 작동하는지 확인하십시오. – ybungalobill

관련 문제