开发者

Can a cast cause a buffer overrun?

Is it possible for a buffer overflow to occur from a cast?

If so, plea开发者_开发百科se 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.


Only indirectly -- for example, if you have a buffer of char, and decide to work with Unicode so you cast the address of the buffer from char * to wchar_t *, but forget to adjust the number of "items" in that space to compensate for a wchar_t (normally) being larger than a 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜