简体   繁体   English

强制转换会导致缓冲区溢出吗?

[英]Can a cast cause a buffer overrun?

Is it possible for a buffer overflow to occur from a cast? 转换是否可能导致缓冲区溢出?

If so, please explain how. 如果是这样,请说明如何。

thanks. 谢谢。

Maybe: 也许:

char p[1];
int *b = static_cast<int *>(p);
*b = 1;

Voila, buffer overrun! 瞧,缓冲区溢出! But only the write would overrun, doing the cast itself is not an overrun. 但是只有写入会溢出,执行强制转换本身并不是溢出。

仅间接地-例如,如果您有一个char缓冲区,并决定使用Unicode,则将缓冲区的地址从char * wchar_t *wchar_t * ,但是忘记将该空间中的“项目”数调整为补偿wchar_t (通常)大于char ...

Not really. 并不是的。 A buffer overrun is caused by writing outside a buffer's boundary. 缓冲区超限是由于在缓冲区边界之外写入而引起的。 So unless you do something stupid like this: 所以除非你做这样的蠢事:

struct overrun
{
    explicit overrun(size_t pX)
    {
        char buffer[1];
        for (size_t i = 0; i < pX; ++i)
            buffer[i] = 5;
    }
};

int main()
{
    static_cast<overrun>(100); // oops
}

A cast isn't going to typically overrun a buffer. 强制转换通常不会超出缓冲区。 (And even here, one could argue it's not the cast that causes the overrun so much as its the construction). (甚至在这里,人们可能会认为,造成超支的原因不是演员,而是造成施工的原因)。 If you're having a real problem, ask. 如果您遇到真正的问题,请询问。

Sort of, I suppose... say you have something like this: 我想...说你有点像这样:

class A
{
};

class B
{
public:
  operator A()
  {
    char buffer[5];
    strcpy(buffer, "1234512345"); // buffer overrun here

    A a;
    return a;
  }
};

// later...

B b;
A a = static_cast<A>(b); // triggers buffer overrun above

Technically, the cast is not required (since it's implicit) but that's one example where you could say it's possible. 从技术上讲,强制转换不是必需的(因为它是隐式的),但这是您可以说是可能的一个示例。 Of course, this is a silly example :-) 当然,这是一个愚蠢的例子:-)

Not sure exactly how your analysis tool reports the culprit, but what about this? 不确定您的分析工具是如何准确报告问题的,但那又如何呢?

char ra[] = "hi";
char &ref = ra[3];
std::cout << static_cast<int>(ref);

Of course it's evaluating the argument of the cast which has actually overrun, rather than the conversion as such. 当然,它是在评估实际已超出转换的转换的参数,而不是转换本身。

GMan says that a read overrun doesn't count, but you could just as well assign the result of a cast to an out-of-bounds location, and some tool appear to report the cast as guilty. GMan表示读取溢出不算在内,但您也可以将强制转换的结果分配到越界位置,并且某些工具似乎将强制转换报告为有罪。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM