When i use malloc() or new to allocate memory,it sometimes gives run time errors, how to avoid these errors?
Asked
Active
Viewed 54 times
-2
Rajeev Singh
- 3,292
- 2
- 19
- 30
-
3Maybe his Question can help you: http://stackoverflow.com/questions/240212/what-is-the-difference-between-new-delete-and-malloc-free – Jan Hohenheim Mar 15 '16 at 10:20
-
When you use `malloc` to allocate memory for an object, instead of `new`, this may lead to the strange errors (object is not initialized). – Gosha U. Mar 15 '16 at 10:20
1 Answers
3
What you malloc(), you need to free().
What you new, you need to delete.
What you new [], you need to delete [].
Any other combination is undefined behaviour.
Besides, new and new [] actually construct object(s) in the allocated memory (which delete / delete[] call the destructor(s) of), while malloc() / free() don't -- they just handle memory, not objects.
That is as much as I can help you, given the (lack of) information given.
DevSolar
- 67,862
- 21
- 134
- 209