Re: Pointer changed unexpectedly.

From: Karl Heinz Buchegger (kbuchegg_at_gascad.at)
Date: 05/17/04


Date: Mon, 17 May 2004 11:23:18 +0200

John wrote:
>
> Karl Heinz Buchegger <kbuchegg@gascad.at> wrote in message news:<40A396AF.C283D092@gascad.at>...
> > John wrote:
> > >
> > > Hi Denis,
> > >
> > > Thanks a lot. You are right. I find that function2() tries to write 11
> > > elements in to array rr.
> > > If I define the size of array rr in function2(), e.g., I put "class2
> > > *rr[10];" in function2(), but function2() still tries to write 11
> > > elements into array rr, what will happen?
> >
> > Nobody knows. It is undefind.
> > Anything can happen.
>
> To prevent it, I add a condition in function2() to check the index, like,
> if(i < 10) rr[i] = r0;
> else std::cout<<"overflow"<<endl;
>
> Is there a better way to do it?

It depends on what function2 does.

If function2 looks something like this:

  for( int i = 0; i <= 10; ++i )
     rr[i] = r0;

Then the simplest thing is to make the for loop correct and
follow the usual C++ idiom

  for( int i = 0; i < 10; ++i )
     rr[i] = r0;

But there are zillion other possible scenarios so a general
answer cannot be given. But it certainly would be a good idea
to pass the array size into that function, to make it independent of
that magical number 10.

> > But a possible scenary would be:
> > You overwrite the return address with some bytes
> > which happen to be a valid address in your system.
> > Unfortunately this is the address of the low level
> > BIOS function which formats your hard drive :-)
>
> oh, like a virus.

Not necessarily. I harmful virus is programmed by a criminal
by intention.

-- 
Karl Heinz Buchegger
kbuchegg@gascad.at