Hi, I am trying to play around with malloc() and free() to learn and test them. So I wrote a little program that stores all the even numbers till 2000 in an array that is allocated using malloc. It is then freed using free(). However, I get an error when the program is ended. Any help is appreciated.
To clarify, you are not allocating enough memory with malloc. You are only allocating space for a single int... whereas you need to allocate space for 1000 ints.
Also, FWIW, you generally should avoid malloc/free in C++.
new[]/delete[] are better
and std::unique_ptr is better still:
If I were you, I'd leave the malloc() family to C where they belong.
This is because they do not play nice with objects that have a non-trivial constructor or destructor i.e. constructors and destructors are not called to initialize the chunk of memory that is allocated.