Kevin Meredith
Kevin Meredith

Reputation: 41909

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.

Upvotes: 1

Views: 587

Answers (5)

Steve Jessop
Steve Jessop

Reputation: 279285

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.

Upvotes: 1

Dean Harding
Dean Harding

Reputation: 72658

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 :-)

Upvotes: 3

GManNickG
GManNickG

Reputation: 503963

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.

Upvotes: 3

Dr. Snoopy
Dr. Snoopy

Reputation: 56377

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.

Upvotes: 4

Jerry Coffin
Jerry Coffin

Reputation: 490178

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...

Upvotes: 3

Related Questions