为何按断点调试结果正确,而运行结果不正确

C++语言 码拜 7年前 (2017-04-28) 1064次浏览
具体代码如下:因代码太多,在下边的回复中贴一些
头文件d_hash.h
#ifndef HASH_CLASS
#define HASH_CLASS
#include <iostream>
#include <vector>
#include <list>
#include <utility>
#include “d_except.h”
using namespace std;
template <typename T, typename HashFunc>
class suhash   //书hash
{
public:
#include “d_hiter.h”
// hash table iterator nested classes
suhash(int nbuckets, const HashFunc& hfunc = HashFunc());
// constructor specifying the number of buckets in the hash table
// and the hash function
suhash(T *first, T *last, int nbuckets, const HashFunc& hfunc = HashFunc());
// constructor with arguments including a pointer range
// [first, last) of values to insert, the number of
// buckets in the hash table, and the hash function
bool empty() const;
// is the hash table empty?
int size() const;
// return number of elements in the hash table
iterator find(const T& item);
const_iterator find(const T& item) const;
// return an iterator pointing at item if it is in the
// table; otherwise, return end()
pair<iterator,bool> insert(const T& item);
// if item is not in the table, insert it and
// return a pair whose iterator component points
// at item and whose bool component is true. if item
// is in the table, return a pair whose iterator
// component points at the existing item and whose
// bool component is false
// Postcondition: the table size increases by 1 if item
// is not in the table
int erase(const T& item);
// if item is in the table, erase it and return 1;
// otherwise, return 0
// Postcondition: the table size decreases by 1 if
// item is in the table
void erase(iterator pos);
// erase the item pointed to by pos.
// Precondition: the table is not empty and pos points
// to an item in the table. if the table is empty, the
// function throws the underflowError exception. if the
// iterator is invalid, the function throws the
// referenceError exception.
// Postcondition: the tree size decreases by 1
void erase(iterator first, iterator last);
// erase all items in the range [first, last).
// Precondition: the table is not empty. if the table
// is empty, the function throws the underflowError
// exception.
// Postcondition: the size of the table decreases by
// the number of elements in the range [first, last)
iterator begin();
// return an iterator positioned at the start of the
// hash table
const_iterator begin() const;
// constant version
iterator end();
// return an iterator positioned past the last element of the
// hash table
const_iterator end() const;
// constant version
private:
int numBuckets;
// number of buckets in the table水桶数
vector<list<T> > bucket;
// the hash table is a vector of lists桶
HashFunc hf;
// hash function
int hashtableSize;
// number of elements in the hash table哈希表大小
};
// constructor. create an empty hash table
template <typename T, typename HashFunc>
suhash<T, HashFunc>::suhash(int nbuckets, const HashFunc& hfunc):
numBuckets(nbuckets), bucket(nbuckets), hf(hfunc),
hashtableSize(0)
{}
// constructor. initialize table from pointer range [first, last)
template <typename T, typename HashFunc>
suhash<T, HashFunc>::suhash(T *first, T *last, int nbuckets, const HashFunc& hfunc):
numBuckets(nbuckets), bucket(nbuckets), hf(hfunc),
hashtableSize(0)
{
T *p = first;
while (p != last)
{
insert(*p);
p++;
}
}
template <typename T, typename HashFunc>
bool suhash<T, HashFunc>::empty() const
{
return hashtableSize == 0;
}
template <typename T, typename HashFunc>
int suhash<T, HashFunc>::size() const
{
return hashtableSize;
}
template <typename T, typename HashFunc>
typename suhash<T, HashFunc>::iterator suhash<T, HashFunc>::find(const T& item)
{
// hashIndex is the bucket number (index of the linked list)
int hashIndex = int(hf(item) % numBuckets);
// use alias for bucket[hashIndex] to avoid indexing
list<T>& myBucket = bucket[hashIndex];
// use to traverse the list bucket[hashIndex]
list<T>::iterator bucketIter;
// returned if we find item
// traverse list and look for a match with item
bucketIter = myBucket.begin();
while(bucketIter != myBucket.end())
{
// if locate item, return an iterator positioned in
// bucket hashIndex at location bucketIter
if (*bucketIter == item)
return iterator(this, hashIndex, bucketIter);
bucketIter++;
}
// return iterator positioned at the end of the hash table
return end();
}
template <typename T, typename HashFunc>
typename suhash<T, HashFunc>::const_iterator
suhash<T, HashFunc>::find(const T& item) const
{
// hashIndex is the bucket number (index of the linked list)
int hashIndex = int(hf(item) % numBuckets);
// use alias for bucket[hashIndex] to avoid indexing
const list<T>& myBucket = bucket[hashIndex];
// use to traverse the list bucket[hashIndex]
list<T>::const_iterator bucketIter;
// returned if we find item
// traverse list and look for a match with item
bucketIter = myBucket.begin();
while(bucketIter != myBucket.end())
{
// if locate item, return an iterator positioned in
// bucket hashIndex at location bucketIter
if (*bucketIter == item)
return const_iterator(this, hashIndex, bucketIter);
bucketIter++;
}
// return iterator positioned at the end of the hash table
return end();
}
template <typename T, typename HashFunc>
pair<typename suhash<T, HashFunc>::iterator,bool>
suhash<T, HashFunc>::insert(const T& item)
{
// hashIndex is the bucket number
int hashIndex = int(hf(item) % numBuckets);
// for convenience, make myBucket an alias for bucket[hashIndex]
list<T>& myBucket = bucket[hashIndex];
// use iterator to traverse the list myBucket
list<T>::iterator bucketIter;
// specifies whether or not we do an insert
bool success;
// traverse list until we arrive at the end of
// the bucket or find a match with item
bucketIter = myBucket.begin();
while (bucketIter != myBucket.end())
if (*bucketIter == item)
break;
else
bucketIter++;
if (bucketIter == myBucket.end())
{
// at the end of the list, so item is not
// in the hash table. call list class insert()
// and assign its return value to bucketIter
bucketIter = myBucket.insert(bucketIter, item);
success = true;
// increment the hash table size
hashtableSize++;
}
else
// item is in the hash table. duplicates not allowed.
// no insertion
success = false;
// return a pair with iterator pointing at the new or
// pre-existing item and success reflecting whether
// an insert took place
return pair<iterator,bool>
(iterator(this, hashIndex, bucketIter), success);
}
template <typename T, typename HashFunc>
void suhash<T, HashFunc>::erase(iterator pos)
{
if (hashtableSize == 0)
throw underflowError(“hash erase(pos): hash table empty”);
if (pos.currentBucket == -1)
throw referenceError(“hash erase(pos): invalid iterator”);
// go to the bucket (list object) and erase the list item
// at pos.currentLoc
bucket[pos.currentBucket].erase(pos.currentLoc);
}
template <typename T, typename HashFunc>
void suhash<T, HashFunc>::erase(typename suhash<T, HashFunc>::iterator first,
typename suhash<T, HashFunc>::iterator last)
{
if (hashtableSize == 0)
throw underflowError(“hash erase(first,last): hash table empty”);
// call erase(pos) for each item in the range
while (first != last)
erase(first++);
}
template <typename T, typename HashFunc>
int suhash<T, HashFunc>::erase(const T& item)
{
iterator iter;
int numberErased = 1;
iter = find(item);
if (iter != end())
erase(iter);
else
numberErased = 0;
return numberErased;
}
template <typename T, typename HashFunc>
typename suhash<T, HashFunc>::iterator suhash<T, HashFunc>::begin()
{
suhash<T, HashFunc>::iterator tmp;
tmp.hashTable = this;
tmp.currentBucket = -1;
// start at index -1 + 1 = 0 and search for a non-empty
// list
tmp.findNext();
return tmp;
}
template <typename T, typename HashFunc>
typename suhash<T, HashFunc>::const_iterator suhash<T, HashFunc>::begin() const
{
suhash<T, HashFunc>::const_iterator tmp;
tmp.hashTable = this;
tmp.currentBucket = -1;
// start at index -1 + 1 = 0 and search for a non-empty
// list
tmp.findNext();
return tmp;
}
template <typename T, typename HashFunc>
typename suhash<T, HashFunc>::iterator suhash<T, HashFunc>::end()
{
suhash<T, HashFunc>::iterator tmp;
tmp.hashTable = this;
// currentBucket of -1 means we are at end of the table
tmp.currentBucket = -1;
return tmp;
}
template <typename T, typename HashFunc>
typename suhash<T, HashFunc>::const_iterator suhash<T, HashFunc>::end() const
{
suhash<T, HashFunc>::const_iterator tmp;
tmp.hashTable = this;
// currentBucket of -1 means we are at end of the table
tmp.currentBucket = -1;
return tmp;
}
#endif   // HASH_CLASS
解决方案

10

至少描述一下,两种模式分别是什么结果呀。

30

有时不将“调用函数名字+各参数值,进入函数后各参数值,中间变量值,退出函数前准备返回的值,返回函数到调用处后函数名字+各参数值+返回值”这些信息写日志到文件中是无论怎么样也发现不了问题在哪里的,包括捕获各种异常、写日志到屏幕、单步或设断点或生成core文件、……这些方法都不行! 写日志到文件参考下面:

//循环向a函数每次发送200个字节长度(这个是固定的)的buffer,
//a函数中需要将循环传进来的buffer,组成240字节(也是固定的)的新buffer进行处理,
//在处理的时候每次从新buffer中取两个字节打印
#ifdef _MSC_VER
    #pragma warning(disable:4996)
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef _MSC_VER
    #include <windows.h>
    #include <process.h>
    #include <io.h>
    #define  MYVOID             void
    #define  vsnprintf          _vsnprintf
#else
    #include <unistd.h>
    #include <sys/time.h>
    #include <pthread.h>
    #define  CRITICAL_SECTION   pthread_mutex_t
    #define  MYVOID             void *
#endif
//Log{
#define MAXLOGSIZE 20000000
#define MAXLINSIZE 16000
#include <time.h>
#include <sys/timeb.h>
#include <stdarg.h>
char logfilename1[]="MyLog1.log";
char logfilename2[]="MyLog2.log";
static char logstr[MAXLINSIZE+1];
char datestr[16];
char timestr[16];
char mss[4];
CRITICAL_SECTION cs_log;
FILE *flog;
#ifdef _MSC_VER
void Lock(CRITICAL_SECTION *l) {
    EnterCriticalSection(l);
}
void Unlock(CRITICAL_SECTION *l) {
    LeaveCriticalSection(l);
}
void sleep_ms(int ms) {
    Sleep(ms);
}
#else
void Lock(CRITICAL_SECTION *l) {
    pthread_mutex_lock(l);
}
void Unlock(CRITICAL_SECTION *l) {
    pthread_mutex_unlock(l);
}
void sleep_ms(int ms) {
    usleep(ms*1000);
}
#endif
void LogV(const char *pszFmt,va_list argp) {
    struct tm *now;
    struct timeb tb;
    if (NULL==pszFmt||0==pszFmt[0]) return;
    vsnprintf(logstr,MAXLINSIZE,pszFmt,argp);
    ftime(&tb);
    now=localtime(&tb.time);
    sprintf(datestr,"%04d-%02d-%02d",now->tm_year+1900,now->tm_mon+1,now->tm_mday);
    sprintf(timestr,"%02d:%02d:%02d",now->tm_hour     ,now->tm_min  ,now->tm_sec );
    sprintf(mss,"%03d",tb.millitm);
    printf("%s %s.%s %s",datestr,timestr,mss,logstr);
    flog=fopen(logfilename1,"a");
    if (NULL!=flog) {
        fprintf(flog,"%s %s.%s %s",datestr,timestr,mss,logstr);
        if (ftell(flog)>MAXLOGSIZE) {
            fclose(flog);
            if (rename(logfilename1,logfilename2)) {
                remove(logfilename2);
                rename(logfilename1,logfilename2);
            }
        } else {
            fclose(flog);
        }
    }
}
void Log(const char *pszFmt,...) {
    va_list argp;
    Lock(&cs_log);
    va_start(argp,pszFmt);
    LogV(pszFmt,argp);
    va_end(argp);
    Unlock(&cs_log);
}
//Log}
#define ASIZE    200
#define BSIZE    240
#define CSIZE      2
char Abuf[ASIZE];
char Cbuf[CSIZE];
CRITICAL_SECTION cs_HEX;
CRITICAL_SECTION cs_BBB;
struct FIFO_BUFFER {
    int  head;
    int  tail;
    int  size;
    char data[BSIZE];
} BBB;
int No_Loop=0;
void HexDump(int cn,char *buf,int len) {
    int i,j,k;
    char binstr[80];
    Lock(&cs_HEX);
    for (i=0;i<len;i++) {
        if (0==(i%16)) {
            sprintf(binstr,"%03d %04x -",cn,i);
            sprintf(binstr,"%s %02x",binstr,(unsigned char)buf[i]);
        } else if (15==(i%16)) {
            sprintf(binstr,"%s %02x",binstr,(unsigned char)buf[i]);
            sprintf(binstr,"%s  ",binstr);
            for (j=i-15;j<=i;j++) {
                sprintf(binstr,"%s%c",binstr,("!"<buf[j]&&buf[j]<="~")?buf[j]:".");
            }
            Log("%s\n",binstr);
        } else {
            sprintf(binstr,"%s %02x",binstr,(unsigned char)buf[i]);
        }
    }
    if (0!=(i%16)) {
        k=16-(i%16);
        for (j=0;j<k;j++) {
            sprintf(binstr,"%s   ",binstr);
        }
        sprintf(binstr,"%s  ",binstr);
        k=16-k;
        for (j=i-k;j<i;j++) {
            sprintf(binstr,"%s%c",binstr,("!"<buf[j]&&buf[j]<="~")?buf[j]:".");
        }
        Log("%s\n",binstr);
    }
    Unlock(&cs_HEX);
}
int GetFromRBuf(int cn,CRITICAL_SECTION *cs,struct FIFO_BUFFER *fbuf,char *buf,int len) {
    int lent,len1,len2;
    lent=0;
    Lock(cs);
    if (fbuf->size>=len) {
        lent=len;
        if (fbuf->head+lent>BSIZE) {
            len1=BSIZE-fbuf->head;
            memcpy(buf     ,fbuf->data+fbuf->head,len1);
            len2=lent-len1;
            memcpy(buf+len1,fbuf->data           ,len2);
            fbuf->head=len2;
        } else {
            memcpy(buf     ,fbuf->data+fbuf->head,lent);
            fbuf->head+=lent;
        }
        fbuf->size-=lent;
    }
    Unlock(cs);
    return lent;
}
MYVOID thdB(void *pcn) {
    char        *recv_buf;
    int          recv_nbytes;
    int          cn;
    int          wc;
    int          pb;
    cn=(int)pcn;
    Log("%03d thdB              thread begin...\n",cn);
    while (1) {
        sleep_ms(10);
        recv_buf=(char *)Cbuf;
        recv_nbytes=CSIZE;
        wc=0;
        while (1) {
            pb=GetFromRBuf(cn,&cs_BBB,&BBB,recv_buf,recv_nbytes);
            if (pb) {
                Log("%03d recv %d bytes\n",cn,pb);
                HexDump(cn,recv_buf,pb);
                sleep_ms(1);
            } else {
                sleep_ms(1000);
            }
            if (No_Loop) break;//
            wc++;
            if (wc>3600) Log("%03d %d==wc>3600!\n",cn,wc);
        }
        if (No_Loop) break;//
    }
#ifndef _MSC_VER
    pthread_exit(NULL);
#endif
}
int PutToRBuf(int cn,CRITICAL_SECTION *cs,struct FIFO_BUFFER *fbuf,char *buf,int len) {
    int lent,len1,len2;
    Lock(cs);
    lent=len;
    if (fbuf->size+lent>BSIZE) {
        lent=BSIZE-fbuf->size;
    }
    if (fbuf->tail+lent>BSIZE) {
        len1=BSIZE-fbuf->tail;
        memcpy(fbuf->data+fbuf->tail,buf     ,len1);
        len2=lent-len1;
        memcpy(fbuf->data           ,buf+len1,len2);
        fbuf->tail=len2;
    } else {
        memcpy(fbuf->data+fbuf->tail,buf     ,lent);
        fbuf->tail+=lent;
    }
    fbuf->size+=lent;
    Unlock(cs);
    return lent;
}
MYVOID thdA(void *pcn) {
    char        *send_buf;
    int          send_nbytes;
    int          cn;
    int          wc;
    int           a;
    int          pa;
    cn=(int)pcn;
    Log("%03d thdA              thread begin...\n",cn);
    a=0;
    while (1) {
        sleep_ms(100);
        memset(Abuf,a,ASIZE);
        a=(a+1)%256;
        if (16==a) {No_Loop=1;break;}//去掉这句可以让程序一直循环直到按Ctrl+C或Ctrl+Break或当前目录下存在文件No_Loop
        send_buf=(char *)Abuf;
        send_nbytes=ASIZE;
        Log("%03d sending %d bytes\n",cn,send_nbytes);
        HexDump(cn,send_buf,send_nbytes);
        wc=0;
        while (1) {
            pa=PutToRBuf(cn,&cs_BBB,&BBB,send_buf,send_nbytes);
            Log("%03d sent %d bytes\n",cn,pa);
            HexDump(cn,send_buf,pa);
            send_buf+=pa;
            send_nbytes-=pa;
            if (send_nbytes<=0) break;//
            sleep_ms(1000);
            if (No_Loop) break;//
            wc++;
            if (wc>3600) Log("%03d %d==wc>3600!\n",cn,wc);
        }
        if (No_Loop) break;//
    }
#ifndef _MSC_VER
    pthread_exit(NULL);
#endif
}
int main() {
#ifdef _MSC_VER
    InitializeCriticalSection(&cs_log);
    InitializeCriticalSection(&cs_HEX);
    InitializeCriticalSection(&cs_BBB);
#else
    pthread_t threads[2];
    int threadsN;
    int rc;
    pthread_mutex_init(&cs_log,NULL);
    pthread_mutex_init(&cs_HEX,NULL);
    pthread_mutex_init(&cs_BBB,NULL);
#endif
    Log("Start===========================================================\n");
    BBB.head=0;
    BBB.tail=0;
    BBB.size=0;
#ifdef _MSC_VER
    _beginthread((void(__cdecl *)(void *))thdA,0,(void *)1);
    _beginthread((void(__cdecl *)(void *))thdB,0,(void *)2);
#else
    threadsN=0;
    rc=pthread_create(&(threads[threadsN++]),NULL,thdA,(void *)1);if (rc) Log("%d=pthread_create %d error!\n",rc,threadsN-1);
    rc=pthread_create(&(threads[threadsN++]),NULL,thdB,(void *)2);if (rc) Log("%d=pthread_create %d error!\n",rc,threadsN-1);
#endif
    if (!access("No_Loop",0)) {
        remove("No_Loop");
        if (!access("No_Loop",0)) {
            No_Loop=1;
        }
    }
    while (1) {
        sleep_ms(1000);
        if (No_Loop) break;//
        if (!access("No_Loop",0)) {
            No_Loop=1;
        }
    }
    sleep_ms(3000);
    Log("End=============================================================\n");
#ifdef _MSC_VER
    DeleteCriticalSection(&cs_BBB);
    DeleteCriticalSection(&cs_HEX);
    DeleteCriticalSection(&cs_log);
#else
    pthread_mutex_destroy(&cs_BBB);
    pthread_mutex_destroy(&cs_HEX);
    pthread_mutex_destroy(&cs_log);
#endif
    return 0;
}

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明为何按断点调试结果正确,而运行结果不正确
喜欢 (0)
[1034331897@qq.com]
分享 (0)