You call free() on the value returned by malloc(). You are not doing this in the code you're showing -- you're calling free() on each of the characters, which is invalid and leads to undefined behavior.
Code:
free(vec);
That's it.
i tried but it gave me a runtime error when it gets to free (vec)
Then you are corrupting the heap somewhere else in your program. You will see that there is nothing wrong when you do this:
Code:
#include <stdlib.h>
int main()
{
char *vec;
int number_of_elements = 100;
vec = (char*) malloc ((sizeof(char))*(number_of_elemets));
free(vec);
}
Do you get a runtime error when you run this program? If not, it is what you're doing in your program between the calls to malloc and free that is causing the problem.
Well..just out of curiosity...is there any special need that you are using a C character array (like limited to C programming)? Otherwise, I would suggest using one of the C++ standard classes 'vector' or 'string' (depending on what your array will contain) which contains their own memory management...
Ciao, Andreas
"Software is like sex, it's better when it's free." - Linus Torvalds
Originally posted by kfaday
i was writing one position over what i reserved
i reserved x places and i wrote the x+1 place
now i can do free (vec) and it works
thanks
And that is one of the best reasons for using the standard 'vector' class instead...as long as you are programming in C++...
Ciao, Andreas
"Software is like sex, it's better when it's free." - Linus Torvalds
Bookmarks