Re: program is not crashing, after 10 iteration
Donkey Hottie wrote:
"Pallav singh" <singh.pallav@gmail.com> wrote in message
news:bdf2cdf2-4a67-4696-9111-8002d8c8425a@l35g2000pra.googlegroups.com
Hi All ,
the program is not crashing, after 10 iteration of the
loop;
int main( )
{
int * ptr = (int *)malloc( 10) ;
while( 1 )
{
printf(" %d \n",*ptr);
ptr++ ;
}
}
Thanks
Pallav Singh
Why do you think it should crash after 10 iterations? You allocate 10
bytes, which may take only 2 ints on a 32-bit machine, so if it crashes,
it might do it after 2 iterations.
But indefinded behaviour is undefined behavior. It may do whatever it
pleases. As it does not write to the unallocated memory, it propably
just prints whatever happens to be there. As you do not initilise the
allocated memory anyhow, the result is undefined from the first
iteration already.
Assuming you're running on a Windows machine with an Intel CPU you'll
probably get a pointer into a hardware page of 4Kb. The compiler is not
required to range check the pointer access, and won't for performance
reasons (and because it's hard!) so it doesn't. You might get a crash
after a thousand or so iterations. (4K / 4 bytes)
On the other hand the pointer might be into a pre-built heap in which
case it'll run until it gets to the first inaccessible address past the
end of the heap. Which could be megabytes.
I'd say to anyone stay away from malloc. It's dangerous. Use the STL
stuff to manage memory, it's much safer.
And if you can come up with a good reason why to use malloc you probably
know enough to know when to break the rule. It occurs to me that _I_
haven't use malloc all year.
Andy