PDA

View Full Version : C++ buffer overrun


liquidchild
04-04-2002, 02:56 PM
as I was sitting in Computer science class, staring midlessly at my screen, I thought, how can you easily crash a computer in c++. I haven't tried it, and I'm not sure that it would work, but I was wondering if you tried to create an array of 10 integers and use a for loop to assign 1000000 values to it, would it the program overwrite into more space on the RAM, or would windows catche this and keep it from doing it.

an example in code would be:

int main
{
int i(10);
for(int a =1; a<= 1000000; ++a)
{
i[a] = 32766;
}
return 0;
}

Would this crash a computer you might think?

phubuh
04-04-2002, 05:59 PM
If you have a half-decent OS that has memory protection, this will not be allowed to happen.

In Linux, you'll get a Segmentation Fault, and Windows will most likely generate a bluescreen with a Forbidden error of sorts - if you fix line 3 which contains a syntax error. :)

sans-hubris
04-04-2002, 07:06 PM
An int takes up the same amount of memory no matter what value it has. So, no that wouldn't work.

liquidchild
04-04-2002, 08:41 PM
since its an array though, the number of integeres would inccrease as u go along, and since u only designated enough space for 10, but are putting in 1000000, it would overwrite on top of other programs and either crash ur computer or causew some sort of error

Dru Lee Parsec
04-04-2002, 10:21 PM
How about this: (Syntax may be wrong but the idea should work)



int main {

int * x, *y;
while(1 == 1) {
*x = 0;
x--;
*y = 0;
y++;
}
}



Since x and y are int pointers the --x walks the pointer down in memory 2 bytes (or 4 depending on your CPU) and fills that area of memory with zeros. y walks up memory and fills with zeros.

You should be able to dangerously zero out memory pretty quickly.

kmj
04-04-2002, 11:28 PM
while(1 == 1) //showin' your java slant? (c:

while (1) is okay in c[++].... we don't have real bools. (well, c++ does, but an if takes anything that may or may not evaluate to zero afaik.

Oh yeah, also, just like phubuh said, any decent OS won't let you write outside your little "sandbox" of memory. The program will crash supahfast, but the computer shouldn't.

sans-hubris
04-05-2002, 12:18 AM
The better way is to just take up all the stack space, but I'll let you figure that one out.

liquidchild
04-05-2002, 01:27 PM
I tested it on 95 and it crashes, but like phubuh said, it wont work on half decent os, such as windows xp, or linux, freebsd, so on...

MattD
04-07-2002, 01:04 AM
how about

char* oops = (char*) malloc(-1);

:)

void f(void){
int x = 999;
while(1)
f();
}

should work too... ;)

Matt D
-= yes, the malloc trick does work on a few old old unix variants ;) =-