shamir shakir <dewswo...@...> wrote:
>
> Hi ,
> I'm having some probs in this code ....
>
> #include <iostream>
> #include <cstdlib>
C++ has built in operators for dynamic allocation and deallocation.
It also has built in container classes. I suggest you learn them in
preference to malloc and free.
> using namespace std ;
>
> #define SIZE 10
> #define EXTRA 50
C++ also has named constant support...
const size_t size_k = 10;
const size_t extra_k = 50;
> int main()
> {
> int *i ;
> int j ;
>
> cout << "Size of int is : " << sizeof(int) << endl ;
> i = (int *)malloc(SIZE) ;
As others have pointed out, malloc allocates bytes. It doesn't
know the intended type of what it is allocating. Instead do...
int *i = new int[size_k];
...
delete[] i;
> if(!i)
> {
> cout << " Allocation error " ;
> exit(1) ;
1 is not a portable exit code for signaling failure.
Use EXIT_FAILURE.
> }
> cout << "After allocating memory... " << SIZE << endl ;
>
> for(j=0; j<(SIZE+EXTRA); j++)
> i[j] = j ;
You are deliberately causing 'buffer overrun'. There is a
wealth of information about how bad this is and why you
should avoid it.
> 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 ?
When you sell your car it doesn't magically disappear in
a cloud of smoke simply because you no longer own it.
Computer memory is often the same.
[Advanced: this is a source of security issues for programs
that deal with password authentication.]
> I'm currently compiling in Code Blocks with GCC compiler.
More importantly, what reference texts do you have? Do they
teach the STL?
--
Peter