写程序常遇到的Bug
来源:互联网 发布:2016年天猫数据 编辑:程序博客网 时间:2024/06/06 05:32
一、浮点数比较
// FloatCompare.cpp : 定义控制台应用程序的入口点。//#include "stdafx.h"#include <iostream>using namespace std;void float_compare(){float a = 3987.25;float b = 3987.25;//Error1//if (((a - 3897.25) > -0.00001) && ((a - 3897.25) < 0.00001))//Error2//if(a == 3987.25;//Correctif (int(a * 100) == 398725)cout << "a == b";elsecout << "a != b";cout << endl;}int _tmain(int argc, _TCHAR* argv[]){float_compare();return 0;}二、死锁
HRESULT CServerDlg::OnStockData(WPARAM wParam, LPARAM lParam){//time_t _now;//time(&_now);//tm* _pTime;//_pTime = localtime(&_now);//switch (_pTime->tm_hour)//{//case 17://{//if (_pTime->tm_min == 30)//return 0;//}//case 23://{//if (_pTime->tm_min == 30)//return 0;//}//default:break;//}if (m_isFirstMsg){::AllocConsole(); // 打开控件台资源freopen("CONOUT$", "w+t", stdout); // 申请写freopen("CONIN$", "r+t", stdin); // 申请读}RCV_DATA*pHeader = (RCV_DATA *)lParam;BOOL bUpdateVar = FALSE;switch (wParam){case RCV_REPORT:// 股票行情{RCV_REPORT_STRUCTEx *pReport;LPBYTE pData = (LPBYTE)pHeader->m_pReport;SetRedraw(FALSE);CString String;m_PacketCount += pHeader->m_nPacketNum;String.Format(_T("%d"), m_PacketCount);BOOL bNeedInvalidate = FALSE;SetWindowText(String);WaitForSingleObject(g_hMutex, INFINITE);for (int i = 0; i < pHeader->m_nPacketNum; i++){pReport = (RCV_REPORT_STRUCTEx *)pData;pData += pReport->m_cbSize;float _newPrice = pReport->m_fNewPrice * 6.1145 / 31.1035 * 1000;float _closePrice = pReport->m_fLastClose * 6.1145 / 31.1035 * 1000;float _openPrice = pReport->m_fOpen * 6.1145 / 31.1035 * 1000;float _highPrice = pReport->m_fHigh * 6.1145 / 31.1035 * 1000;float _lowPrice = pReport->m_fLow * 6.1145 / 31.1035 * 1000;time_t _now;time(&_now);if (m_isServerSarted){if (!strcmp("XAG", pReport->m_szLabel)){if (m_isFirstMsg){NEW_PRICE _objNewPrice;_objNewPrice._time = _now;_objNewPrice._newPrice = pReport->m_fNewPrice;m_newPrices.push_back(_objNewPrice);m_isFirstMsg = false;}if (!g_newPrices.empty()){for (std::vector<NEW_PRICE>::iterator it = m_newPrices.begin(); it != m_newPrices.end(); it++){if (it->_time - _now > 180){m_newPrices.erase(it);break;}}std::cout << "===========================================================" << std::endl;int _index = 1;for (std::vector<NEW_PRICE>::iterator it = m_newPrices.begin(); it != m_newPrices.end(); it++){float temp = it->_newPrice;std::cout << "element_" << _index++ << ":" << it->_newPrice << std::endl;}std::cout << "----------------------------------" << std::endl;_index = 1;for (std::vector<NEW_PRICE>::iterator it = m_newPrices.begin(); it != m_newPrices.end(); it++){float temp = it->_newPrice;std::cout << "element_" << _index++ << ":" << it->_newPrice << " newprice:" << pReport->m_fNewPrice << std::endl;//if (temp - _newPrice > -0.00001 && temp - _newPrice < 0.00001)if ((int)(temp * 100) == (int)(pReport->m_fNewPrice * 100)){std::cout << "find repeated data with 3 minutes, so return !" << std::endl;//如果没有这句,就死锁了!ReleaseMutex(g_hMutex);return 0;}}}std::cout << "no repeated data with 3 minutes, so send -->" << std::endl;NEW_PRICE _objNewPrice;_objNewPrice._time = pReport->m_time;_objNewPrice._newPrice = pReport->m_fNewPrice;m_newPrices.push_back(_objNewPrice);time_t _now = pReport->m_time;tm* pTime = localtime(&_now);char chSrz[256] = {};memset(chSrz, 0, sizeof(chSrz));//sprintf_s(chSrz, "%s %d %d %.3f %.3f %.3f %.3f %.3f\r\n",//pReport->m_szLabel,//1:产品标志 XAU为白银,其他的暂时还不需要//100,//2:产品代码 现在所有的产品的代码都是100,这个代码以后要改//pReport->m_time,//3:时间(1970年到现在的秒数)//pReport->m_fNewPrice,//4:最新价格//pReport->m_fLastClose,//5:昨天收盘价//pReport->m_fOpen,//6:开盘价//pReport->m_fHigh,//7:最高价//pReport->m_fLow//8:最低价//);sprintf_s(chSrz, "%s %d %d-%d-%d %d:%d:%d %.3f %.3f %.3f %.3f %.3f\r\n",pReport->m_szLabel,//1:产品标志 XAU为白银,其他的暂时还不需要100,//2:产品代码 现在所有的产品的代码都是100,这个代码以后要改//pReport->m_time,//3:时间(1970年到现在的秒数)pTime->tm_year + 1900, pTime->tm_mon + 1, pTime->tm_mday, pTime->tm_hour, pTime->tm_min, pTime->tm_sec,pReport->m_fNewPrice,//4:最新价格pReport->m_fLastClose,//5:昨天收盘价pReport->m_fOpen,//6:开盘价pReport->m_fHigh,//7:最高价pReport->m_fLow//8:最低价);if (!connCheckQueue.empty()){for (std::deque<CONNID>::iterator it = connQueue.begin(); it != connQueue.end(); it++){m_Server.Send(*it, (const BYTE*)chSrz, strlen(chSrz));}}}}}ReleaseMutex(g_hMutex);SetRedraw(TRUE);break;}}//::FreeConsole();return 0;}
三、还是死锁
逻辑性死锁
//线程1:WaitForSingleObject(m_mutex1)// code...WaitForSingleObject(m_mutex2)// code ...ReleaseMutex(m_mutex2)// code ...ReleaseMutex(m_mutex1)//线程2:WaitForSingleObject(m_mutex2)// code...WaitForSingleObject(m_mutex1)// code ...ReleaseMutex(m_mutex1)// code ...ReleaseMutex(m_mutex2)
这种情况在做异步存数据库是遇到过,找了很久才查出来!
四、低级错误
STOCK_PRICE _stockPrice;strcpy(_stockPrice.m_szLabel, pReport->m_szLabel);_stockPrice.m_iCode = 100;_stockPrice.m_currentTime = pReport->m_time;//_stockPrice.m_fNewPrice = pReport->m_fNewPrice;_stockPrice.m_fLastClose = pReport->m_fLastClose;_stockPrice.m_fOpenPrice = pReport->m_fOpen;_stockPrice.m_fHighPrice = pReport->m_fHigh;_stockPrice.m_fLowPrice = pReport->m_fLow;g_stockRawPriceQueue.push_back(_stockPrice);
少给一个数据成员赋值。
四、逻辑错误
else if (((*it).connID == dwConnID) && ((*it).flagLogin == 0xFF)){//std::cout << "Disconnect socket:" << dwConnID << endl;if (m_Server.Disconnect(dwConnID))::LogDisconnect(dwConnID);else::LogDisconnectFail(dwConnID);break;}
五、接口类构造函数没实现,它的继承函数也没有交代
//Strategy.hclass IStrategy{public:IStrategy(/*void*/);virtual ~IStrategy(/*void*/);virtual void Operate(/*void*/) = 0;};//BackDoor.hclass CBackDoor :public IStrategy{public:CBackDoor(/*void*/);~CBackDoor(/*void*/);void Operate(/*void*/);};//BackDoor.cpp#include "StdAfx.h"#include "BackDoor.h"#include <iostream>using std::cout;using std::endl;CBackDoor::CBackDoor(){}CBackDoor::~CBackDoor(){}void CBackDoor::Operate(){cout << "找乔国老帮忙,让吴国太给孙权施加压力" << endl;}
六、VS2013本身的bug
在VS2013中进行调试是,有时候,特别是调用多个动态库的时候,变量的值会显示错误,或者不显示,这时候如果要看变量的值,最好打印出来。
七、类中有指针类型的成员,在函数中返回该类的一个值类型的对象,或以值得方式传入对象,或将一个对象初始化另一个对象,一定要重写拷贝构造函数和赋值重载函数。
如果没有这两个函数,则应该用指针或引用的方式取代值得方式。
//DataBuffer.h/********************************************************************File :DataBuffer.hCreation date :2010/6/27License :Copyright 2010 Ahmed Charfeddine, http://www.pushframework.com Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.*********************************************************************/#ifndef DataBuffer__INCLUDED#define DataBuffer__INCLUDED#pragma once#include "PushFramework.h"namespace PushFramework{class PUSHFRAMEWORK_API DataBuffer{public: DataBuffer(unsigned int uMaxSize); DataBuffer(); ~DataBuffer(void); void allocate(unsigned int uMaxSize); bool append(char* _pBuffer, unsigned int _uSize); bool append(unsigned char* _pBuffer, unsigned int _uSize); void pop(unsigned int _uSize); unsigned int getDataSize(); unsigned int getMaxDataSize(); char* getBuffer(); void growSize(unsigned int growBy); unsigned int getRemainingSize(); char getAt(int offset);private: char* pBuffer; unsigned int uSize; unsigned int uMaxSize;};}#endif // DataBuffer__INCLUDED
//DataBuffer.cpp/********************************************************************File :DataBuffer.cppCreation date :2010/6/27License :Copyright 2010 Ahmed Charfeddine, http://www.pushframework.com Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.*********************************************************************/#include "StdAfx.h"#include "../include/DataBuffer.h"namespace PushFramework{DataBuffer::DataBuffer(unsigned int uMaxSize){ uSize = 0; allocate(uMaxSize);}DataBuffer::DataBuffer(){ uSize = 0; pBuffer = NULL;}void DataBuffer::allocate( unsigned int uMaxSize ){ this->uMaxSize = uMaxSize; pBuffer = new char[uMaxSize];}DataBuffer::~DataBuffer(void){ delete[] pBuffer;}bool DataBuffer::append( char* _pBuffer, unsigned int _uSize ){ if(getRemainingSize() < _uSize) return false; //Copy the data : ::memcpy(pBuffer+uSize, _pBuffer, _uSize); //Update the size of the buffer. uSize+=_uSize; return true;}bool DataBuffer::append( unsigned char* _pBuffer, unsigned int _uSize ){ return append((char*) _pBuffer, _uSize);}void DataBuffer::pop( unsigned int _uSize ){ uSize -= _uSize; if(uSize == 0){ return; } ::memmove(pBuffer, pBuffer+_uSize, uSize);}unsigned int DataBuffer::getDataSize(){ return uSize;}unsigned int DataBuffer::getMaxDataSize(){ return uMaxSize;}char* DataBuffer::getBuffer(){ return pBuffer;}unsigned int DataBuffer::getRemainingSize(){ return uMaxSize - uSize;}void DataBuffer::growSize( unsigned int growBy ){ uSize += growBy;}char DataBuffer::getAt( int offset ){ return pBuffer[offset];}}
//OperatePacket.h#pragma onceclass OperatePacket{public:enum{Disconnected = 1,Connecting,Connected,WaitingToClose};enum{ResultOK = 0,ResultTryAgain,ResultFailed,};OperatePacket();~OperatePacket();int serializePacket(PushFramework::OutgoingPacket* a_pPacket);void setProtocol(PushFramework::Protocol* pProtocol);//PushFramework::DataBuffer getData() const;PushFramework::DataBuffer* getData() const;void Print(PushFramework::DataBuffer& a_data) const;private:PushFramework::Protocol* pProtocol;PushFramework::DataBuffer oBuffer;PushFramework::DataBuffer* pOBuffer;static unsigned int m_uDataBufferSize;};extern OperatePacket theApp;
//OperatePacket.cpp#include "stdafx.h"#include "OperatePacket.h"#include <stdio.h>unsigned int OperatePacket::m_uDataBufferSize = 1024 * 8;OperatePacket::OperatePacket() : oBuffer(m_uDataBufferSize){//oBuffer.allocate(m_uDataBufferSize);pOBuffer = new PushFramework::DataBuffer(1024 * 8);}OperatePacket::~OperatePacket(){}int OperatePacket::serializePacket(PushFramework::OutgoingPacket* a_pPacket){EchoRequestPerson* pPacket = (EchoRequestPerson*)a_pPacket;cout << "Name:" << pPacket->Name() << " ID:" << pPacket->ID() << " Birthday:" << pPacket->Birthday() << endl;unsigned int uWrittenBytes = 0;cout << "the Maxsize of oBuffer is " << oBuffer.getMaxDataSize() << endl;int iResult = pProtocol->serializeOutgoingPacket(*pPacket, oBuffer, uWrittenBytes);iResult = pProtocol->serializeOutgoingPacket(*pPacket, *pOBuffer, uWrittenBytes);//char szTest[1024] = { 0 };//strncmp(szTest, oBuffer.getBuffer() + 6, oBuffer.getDataSize() - 6);//for (int i = 0; i < oBuffer.getDataSize() - 7; i++)//{//printf("%c", oBuffer.getAt(i + 6));//}//cout << endl;if (iResult == PushFramework::Protocol::eInsufficientBuffer){//The intermediate buffer is still full.//Caller should try later when pending write operation succeed and make some room in the buffer.return ResultTryAgain;}if (iResult != PushFramework::Protocol::Success){//For any other reason, caller should not retry with the same packet.return ResultFailed;}}void OperatePacket::setProtocol(PushFramework::Protocol* pProtocol){this->pProtocol = pProtocol;}//PushFramework::DataBuffer OperatePacket::getData() const//{//return oBuffer;//}PushFramework::DataBuffer* OperatePacket::getData() const{return pOBuffer;}void OperatePacket::Print(PushFramework::DataBuffer& a_data) const{for (int i = 0; i < a_data.getDataSize() - 8; i++){printf("%c", a_data.getAt(i + 6));}cout << endl;}OperatePacket theApp;
0 0
- 写程序常遇到的Bug
- 写记事本程序遇到的文件Bug
- iOS -- 界面跳转--常遇到的bug
- uva常遇到bug
- 【iOS开发】 常遇到的Crash和Bug处理
- Java初级开发中常常遇到的Bug 系列
- html&css 新手入门常遇到的bug总结
- 写html静态页面常遇到的问题
- 运行Java程序时 常遇到的错误
- 常遇到的陷阱
- 常遇到的异常
- 常遇到的异常
- 写代码的时候遇到的BUG小结
- 写php下载图片时遇到的bug
- 写反转二叉树中遇到的一个小Bug
- 写小程序遇到的问题
- 写程序都会遇到的问题, DPI
- 今天写程序遇到的一些问题
- 年终复盘,我的2012
- C++程序设计实践学材系列(19)——1.4.2 输出两数中大值程序的其他写法
- 晶体管放大电路之频率补偿
- Centos ifconfig 的配置文件
- qwtplot3D安装及运行-----终结解决方案
- 写程序常遇到的Bug
- GetLastError的返回值的含义
- Java调用svnkit,检出指定版本的文件
- JVM原理
- 字符串数组的最长公共前缀
- JS打印指定区域内容
- GetWindowRect、GetClientRect、ScreenToClient与ClientToScreen
- GCD ios多线程 runloop
- DirectUI皮肤之旅