The good news for gcc users is that when using gcc 5.1 and higher, it will be easier for them to quickly find such a common error in calculating the size of an array declared as a function parameter:void something( char arr[100] ) { // this loop is broken for( size_t index = 0; index < sizeof(arr)/sizeof(arr[0]); index++ ) { //WHATEVER } } void something( char encryptionKey[9000] ) { // WHATEVER, PROFIT // this call is broken SecureZeroMemory( encryptionKey, sizeof(encryptionKey)); // erase the key } template<typename StoredType, size_t Size> char ( &ArrayElementsCountHelper(StoredType( &Array )[Size]) )[Size]; #define countOfElements(Array) sizeof(ArrayElementsCountHelper (Array)) char arr[100] for( size_t index = 0; index < countOfElements(arr); index++ ) { //WHATEVER } // in a header far, far away... #define errorProneCountOfElements( arr ) (sizeof(arr)/sizeof((arr)[0])) for( size_t index = 0; index < errorProneCountOfElements (arr); index++ ) { //WHATEVER } void somethingExplicitCount( char arr[] ) { for( size_t index = 0; index < sizeof(arr)/sizeof(arr[0]); index++ ) { //WHATEVER } } void somethingMacroCount( char arr[9000] ) { for( size_t index = 0; index < errorProneCountOfElements(arr); index++ ) { //WHATEVER, PROFIT } } void somethingMemset( char key[9000] ) { //WHATEVER, PROFIT memset(key, 0, sizeof(key)); // don't use memset for sensitive data } Source: https://habr.com/ru/post/263609/
All Articles