C++:找BUG~
下面有個函數,用于將6個字節的字符數組‘轉換’到12字節。例如:






因為目標是字符串風格,為了顯示需要,dst實際使用的是13字節長度數組,如下:



函數如下,麻煩找下Bug。
























































<----郁悶的分割線---->
Y的,白癡的錯誤搞了我兩天。。。。
posted on 2011-01-18 17:10 codejie 閱讀(1999) 評論(18) 編輯 收藏 引用 所屬分類: C++ 、隨筆而已
Using C++
posted on 2011-01-18 17:10 codejie 閱讀(1999) 評論(18) 編輯 收藏 引用 所屬分類: C++ 、隨筆而已
把兩個 *id = 0都改成
*id = '0'; 回復 更多評論
*id = t + 'a';
應為
*id = t - 10 + 'a';
封裝
inline unsigned char digit2char(unsigned char d)
{
assert(d < 0x10);
if (d < 10)
{
return d +'0';
}
else
{
return d - 10 + 'a';
}
} 回復 更多評論
inline unsigned char digit2char(unsigned char d)
{
assert(d < 0x10);
return "0123456789abcdef"[d];
} 回復 更多評論
#include<stdio.h>
unsigned char src[6] = { 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc};
void makeId(unsigned char* id, const unsigned char* ptr)
{
int i = 0;
while(i < 6)
{
unsigned char t = *ptr >> 4;
if(t >= 0 && t <= 9)
{
*id = t + '0';
}
else if(t >= 0x0a && t <= 0x0f)
{
*id = t + 'a'-10;
}
else
{
*id = 0;
}
t = (*ptr & 0x0F);
++ id;
if(t >= 0 && t <= 9)
{
*id = t + '0';
}
else if(t >= 0x0a && t <= 0x0f)
{
*id = t + 'a'-10;
}
else
{
*id = 0;
}
++ ptr;
++ id;
++ i;
}
*id = '\0';
}
int main()
{
unsigned char dst[13];
makeId(dst, src);
puts((char*)dst);
return 0;
} 回復 更多評論
@kkk
恩,可以這樣。但這里設置為0,而不是‘0’,用于代表出錯情況。 回復 更多評論
@hello
是的。一看就是搞C++的,喜歡封裝。。。 回復 更多評論
@Lucifer
要是按照中國教育標準看,這個是標準答案。。。我是找了兩天才發現。。。
最關鍵是就是最后的那個--‘*id = '\0';‘我直接id[12]=0,導致覆蓋其他數據了。。。白癡啊我。。。 回復 更多評論
據說在每一個軟件公司里,都有一個掃地的老太太。很偶然地,當她經過一個程序員的身邊,掃一眼屏幕上的代碼,會低聲提醒對方說:小心,緩沖溢出了。 回復 更多評論
我手頭上也有一些問題要提問...能夠幫我找下嗎? thanks.
Q1: 下列那邊有問題?
class A
{
A(){};
protected:
double _a;
public:
A(double a) : _a(a) {}
double eval(double a1)
{
return _a * a1;
}
virtual ~A(){}
};
class B : public A
{
public:
double eval( double b )
{
_a = _a * b;
return _a;
}
};
class C
{
public:
C() : _myA(0) {}
double _a;
A* _myA;
~C()
{
if ( _myA != 0 )
delete _myA;
}
};
class D : public A, public C
{
public:
int run(double d) { return d + _a; }
};
Q2:以下找出錯誤跟可能的危險
void main()
{
A* testB = new B;
double testVal = b.eval( 4.0 );
C testC;
testC._myA = new A(4);
C testC2 = testC;
D testD;
int testVal2 = testD.run( 3.0 );
delete testB;
}
Q3:以下程式那邊造成complier有問題? 可以保留SetValue的Const-ness嗎? 如果可以,怎麼修改?
class cTest
{
public:
cTest(){};
~cTest(){};
void SetValue( const double val ) const
{
m_value = val;
}
private:
double m_value;
};
Q4:以下程式是否有memory leak問題, 如果有,怎麼避免?
class cTest
{
public:
cTest(){};
~cTest(){};
private:
double m_double[100];
};
void function( cTest* test )
{
delete test;
test = new cTest();
}
void main( void )
{
cTest *t = new cTest();
function( t );
delete t;
} 回復 更多評論
@abeng
這個到不一定,要看實際需要了,畢竟并不是所有的字符數組要做字符串用的,也許就是個字符集會呢? 回復 更多評論
@Max
兄弟,你這不是找bug啊,是在出考試題吧。。。 回復 更多評論
for ( i = 0; i < 6; i++){
sprintf(dest[i*2],"%02x",(unsigned char)src[i]);
} 回復 更多評論
只有注冊用戶登錄后才能發表評論。 | ||
【推薦】100%開源!大型工業跨平臺軟件C++源碼提供,建模,組態!
![]() |
||
相關文章:
|
||
網站導航:
博客園
IT新聞
BlogJava
博問
Chat2DB
管理
|
||
|