photo credit: lincolnblues via photopin cc
はじめに
とあるコードをVisual Studio 2013でコード分析をかけたら以下の警告が表示されました。
警告 C6305: sizeof 数と countof 数の間で不一致が発生した可能性があります.
C6305の警告の意味について調べてみました。
アドレスの型によって進むサイズが違う
たとえば、以下のコード。
sizeof(int)の4byteだけ、変数pに格納されたアドレスをずらそうとしているのですが、実際は4×4の16byte先にずれます。
これは変数pがint型のポインタ変数として定義されているためです。
#include "stdafx.h" #include <stdlib.h> int _tmain(int argc, _TCHAR* argv[]) { int *p = (int*)malloc(20); printf("0x%08x\n", p); //>>0x00387478 int cb = sizeof(int); p +=cb; // warning 6305 printf("0x%08x\n", p); //>>0x00387488 return 0; }
4byteだけずらす場合は、p+=1で良いです。
#include "stdafx.h" #include <stdlib.h> int _tmain(int argc, _TCHAR* argv[]) { int *p = (int*)malloc(20); printf("0x%08x\n", p); //>>0x002a7478 p += 1; printf("0x%08x\n", p); //>>0x002a747c return 0; }
ちなみにchar型のポインタ変数の場合は、+1で1byteずれるので、以下のコードでも4byteだけずれることになります。
#include "stdafx.h" #include <stdlib.h> int _tmain(int argc, _TCHAR* argv[]) { char *p = (char*)malloc(20); printf("0x%08x\n", p); //>>0x004e7478 int cb = sizeof(int); p +=cb; // warning 6305 printf("0x%08x\n", p); //>>0x004e747c return 0; }
関連記事
- 【cppcheck】Variable 'xxx' is reassigned a value before the old one has been used.
- Visual C++ 2013でDLLを作成して動的読み込みしてみる。
- 【cppcheck】The code contains characters that are unhandled. Neither unicode nor extended ASCII are supported.
- 【cppcheck】Size of pointer 'xxx' used instead of size of its data.
- 【cppcheck】Checking if unsigned variable 'xxx' is less than zero.