缓冲区''访问超出界限

时间:2013-06-14 15:34:52

标签: c buffer

在使用静态代码分析工具cppcheck(http://sourceforge.net/apps/mediawiki/cppcheck/index.php?title=Main_Page)进行检查时,该工具发现代码中存在严重错误:

#define MAX_PICTURE_HISTORY 10

#define PICTURE_INTERLACED_ODD 1
#define PICTURE_INTERLACED_EVEN 2

typedef struct
{
    unsigned char* pData;
    unsigned int Flags;
} TPicture;


typedef struct
{
    TPicture* PictureHistory[MAX_PICTURE_HISTORY];
    unsigned char *Overlay;
    unsigned int OverlayPitch;
    unsigned int LineLength;
    int FrameWidth;
    int FrameHeight;
    int FieldHeight;
    MEMCPY_FUNC* pMemcpy;
    unsigned int InputPitch;
} TDeinterlaceInfo;

代码:

TPicture Picture[ 8 ];
int stride = (width*2);
int i;

Info.FieldHeight = height / 2;
Info.FrameHeight = height;
Info.FrameWidth = width;
Info.InputPitch = stride*2;
Info.LineLength = stride;
Info.OverlayPitch = outstride;
Info.pMemcpy = fast_memcpy;

Picture[ 0 ].pData = data->f0 + stride;
Picture[ 0 ].Flags = PICTURE_INTERLACED_ODD;

Picture[ 1 ].pData = data->f0;
Picture[ 1 ].Flags = PICTURE_INTERLACED_EVEN;

Picture[ 2 ].pData = data->f1 + stride;
Picture[ 2 ].Flags = PICTURE_INTERLACED_ODD;

Picture[ 3 ].pData = data->f1;
Picture[ 3 ].Flags = PICTURE_INTERLACED_EVEN;

Picture[ 4 ].pData = data->f2 + stride;
Picture[ 4 ].Flags = PICTURE_INTERLACED_ODD;

Picture[ 5 ].pData = data->f2;
Picture[ 5 ].Flags = PICTURE_INTERLACED_EVEN;

for( i = 0; i < MAX_PICTURE_HISTORY; i++ ) {
    Info.PictureHistory[ i ] = &(Picture[ i ]);   /* <-- The buffer Picture is accessed out of bounds */
}

上面的代码似乎没有任何问题。任何想法为什么这些被拾起,以及如何解决这个问题? 最好的问候。

3 个答案:

答案 0 :(得分:4)

MAX_PICTURE_HISTORY定义为10,但Picture只有8个元素

答案 1 :(得分:1)

你有

#define MAX_PICTURE_HISTORY 10

然后

TPicture Picture[ 8 ];

for( i = 0; i < MAX_PICTURE_HISTORY; i++ ) {
    Info.PictureHistory[ i ] = &(Picture[ i ]);   /* <-- The buffer Picture is accessed out of bounds */
}

访问的元素比提供的要多两个。

答案 2 :(得分:0)

该消息是值得的。你的图片数组有8个元素(0..7),而循环运行到MAX_PICTURE_HISTORY&lt; 10访问数组之外​​的元素8和9。

如果您使用

,代码将更清晰并防止出现错误
 TPicture Picture[ MAX_PICTURE_HISTORY ];

而不是硬编码的8。