1.數值溢出
存儲數據時要考慮數值溢出的問題,選擇合適的類型,特別要注意數值運算時的數值範圍是否合適。比方說,如果使用了int類型,儘管數據本身沒有超範圍,但是在進行乘法計算時卻可能會產生數值溢出。
c++類型的數值範圍速查表:
Type | Typical Bit Width | Typical Range |
---|---|---|
char | 1byte | -127 to 127 or 0 to 255 |
unsigned char | 1byte | 0 to 255 |
signed char | 1byte | -127 to 127 |
(signed) int | 4bytes | -2147483648 to 2147483647,約10^9,或+/- 2^31 |
unsigned int | 4bytes | 0 to 4294967295,約10^9,或2^32 |
(signed) short int | 2bytes | -32768 to 32767 |
unsigned short int | 2bytes | 0 to 65,535 |
(signed) long int | 4bytes | -2,147,483,648 to 2,147,483,647 |
unsigned long int | 4bytes | 0 to 4,294,967,295 |
(signed) long long | 8bytes | -9223372036854775808 to +9223372036854775807,約10^18,或+/- 2^63 |
unsigned long long | 8bytes | 0 to 1844674407370955161,約10^18,或2^64 |
float | 4bytes | +/- 3.4e +/- 38 (~7 digits) |
double | 8bytes | +/- 1.7e +/- 308 (~15 digits) |
long double | 8bytes | +/- 1.7e +/- 308 (~15 digits) |
wchar_t | 2 or 4 bytes | 1 wide character |
2.memset初始化
在做一些編程題時,有時會定義一個全局的大數組並重複使用,這時要記得在每個case開始時用memset函數初始化一下。否則會產生很隱蔽的bug。
3.函數棧溢出
我們知道函數的局部變量是存儲在棧空間裏的,而棧空間一般只有4Mb或者8Mb(跟系統有關)。所以當函數局部變量定義得過大(例如一個大數組),就很容易導致棧溢出錯誤。除此之外,函數的遞歸深度過大也會導致棧溢出。
這裏複習一下,一個由C/C++編譯的程序佔用的內存分爲以下幾個部分:
1、棧區(stack):又編譯器自動分配釋放,存放函數的參數值,局部變量的值等,其操作方式類似於數據結構的棧。
2、堆區(heap):一般是由程序員分配釋放,若程序員不釋放的話,程序結束時可能由OS回收,值得注意的是他與數據結構的堆是兩回事,分配方式倒是類似於數據結構的鏈表。
3、全局區(static):也叫靜態數據內存空間,存儲全局變量和靜態變量,全局變量和靜態變量的存儲是放一塊的,初始化的全局變量和靜態變量放一塊區域,沒有初始化的在相鄰的另一塊區域,程序結束後由系統釋放。
4、文字常量區:常量字符串就是放在這裏,程序結束後由系統釋放。
5、程序代碼區:存放函數體的二進制代碼。
4.make_pair出錯
string str = "asd";
int pos = 1;
make_pair<string, int>(str, pos);
上面的代碼會報錯:no matching function for call to 'make_pair(std::string&, size_t&)',這是因爲make_pair在c++11前後修改了聲明:
// 定義於頭文件 <utility>
// C++11前
template< class T1, class T2 >
std::pair<T1,T2> make_pair( T1 t, T2 u );
// C++11起,C++14前
template< class T1, class T2 >
std::pair<V1,V2> make_pair( T1&& t, T2&& u );
// C++14起
template< class T1, class T2 >
constexpr std::pair<V1,V2> make_pair( T1&& t, T2&& u );
對於該錯誤,有兩種修改方式:
1、make_pair(str, pos)
2、make_pair<string, int>(string(str), int(pos))