Wednesday, 15 June 2011

How could it get more memory than I wanted?(C++) -



How could it get more memory than I wanted?(C++) -

this question has reply here:

why doesn't programme crash when write past end of array? 8 answers

i wanted take 1 integer memory, how programme can work?

code:

#include<iostream> using namespace std; int main(){ int* k=new int[1]; for(int i=0;i<5;i++) cin>>k[i]; for(int i=0;i<5;i++) cout<<k[i]<<"\n"; delete[] k; homecoming 0; }

input:

999999 999998 999997 999996 999995

output:

999999 999998 999997 999996 999995

you invoked undefined behavior accessing memory did not allocate. works purely "by chance". literally every behavior of programme legal, including programme ordering pizza, ...

this work in practice of time because os not give 4 byte or this, whole page of memory (often 4kb) emphasize this: you can never rely on behavior!

c++ memory allocation

No comments:

Post a Comment