first: you should use new, not malloc.
Second, you allocate a block of memory of 40 bytes, or 10 integers, and use
extra--why? just do:
int *i=new int(10);
int j;
for (j=0;j<10;j++)
{
i[j]=j;
}
HTH,
On Jan 20, 2010, at 1:39 PM, shamir shakir wrote:
> Hi ,
> I'm having some probs in this code ....
>
> #include <iostream>
> #include <cstdlib>
> using namespace std ;
>
> #define SIZE 10
> #define EXTRA 50
> int main()
> {
> int *i ;
> int j ;
>
> cout << "Size of int is : " << sizeof(int) << endl ;
> i = (int *)malloc(SIZE) ;
> if(!i)
> {
> cout << " Allocation error " ;
> exit(1) ;
> }
> cout << "After allocating memory... " << SIZE << endl ;
>
> for(j=0; j<(SIZE+EXTRA); j++)
> i[j] = j ;
>
> for(j=0; j<(SIZE+EXTRA); j++)
> cout << "\t" << j << " : "<< i[j] << endl ;
>
> free(i) ;
>
> cout << "after freeing memory ..... " << endl ;
>
> for(j=0; j<(SIZE+EXTRA); j++)
> cout << "\t" << j << " : "<< i[j] << endl ;
>
> return 0 ;
> }
>
> I'm new to dynamic allocation. When i compile this code, some strange things
> happen. Here, I allocate 10 new intizer. But assigning value upto 50 intizer
> (using EXTRA in for loops) give me no error . Why was that happen since a
> I've assigned only 10 ?
>
> Another problem is when I free those memory, still it gives me the same
> value as before freeing the memory. Why are those values kept still there
> and how ?
>
> I'm currently compiling in Code Blocks with GCC compiler.
>
> Thank in advance :)
>
> --
> Shamir Shakir
> http://www.DewsWorld.741.com
>
> :::.:.......... Hope never ends...........:::::
>
> [Non-text portions of this message have been removed]
>
>
[Non-text portions of this message have been removed]
------------------------------------
To unsubscribe, send a blank message to
<mailto:[email protected]>.Yahoo! Groups Links
<*> To visit your group on the web, go to:
http://groups.yahoo.com/group/c-prog/
<*> Your email settings:
Individual Email | Traditional
<*> To change settings online go to:
http://groups.yahoo.com/group/c-prog/join
(Yahoo! ID required)
<*> To change settings via email:
[email protected]
[email protected]
<*> To unsubscribe from this group, send an email to:
[email protected]
<*> Your use of Yahoo! Groups is subject to:
http://docs.yahoo.com/info/terms/